import { describe, it, expect } from 'vitest';
import { prefillFromPromotion } from './promotion-prefill';
import type { AlertRuleResponse } from '../../../api/queries/alertRules';

function fakeRule(overrides: Partial<AlertRuleResponse> = {}): AlertRuleResponse {
  return {
    id: '11111111-1111-1111-1111-111111111111',
    environmentId: '22222222-2222-2222-2222-222222222222',
    name: 'High error rate',
    description: undefined,
    severity: 'CRITICAL',
    enabled: true,
    conditionKind: 'ROUTE_METRIC',
    condition: {
      kind: 'RouteMetricCondition',
      scope: { appSlug: 'orders' },
    } as unknown as AlertRuleResponse['condition'],
    evaluationIntervalSeconds: 60,
    forDurationSeconds: 0,
    reNotifyMinutes: 60,
    notificationTitleTmpl: '{{rule.name}}',
    notificationMessageTmpl: 'msg',
    webhooks: [],
    targets: [],
    createdAt: '2026-04-01T00:00:00Z',
    createdBy: 'alice',
    updatedAt: '2026-04-01T00:00:00Z',
    updatedBy: 'alice',
    ...overrides,
  };
}

describe('prefillFromPromotion', () => {
  it('appends "(copy)" to name', () => {
    const { form } = prefillFromPromotion(fakeRule());
    expect(form.name).toBe('High error rate (copy)');
  });

  it('warns + clears agentId when source rule is agent-scoped', () => {
    const { form, warnings } = prefillFromPromotion(
      fakeRule({
        conditionKind: 'AGENT_STATE',
        condition: {
          kind: 'AgentStateCondition',
          scope: { appSlug: 'orders', agentId: 'orders-0' },
          state: 'DEAD',
          forSeconds: 60,
        } as unknown as AlertRuleResponse['condition'],
      }),
    );
    expect(form.agentId).toBe('');
    expect(warnings.find((w) => w.field === 'scope.agentId')).toBeTruthy();
  });

  it('warns if app does not exist in target env', () => {
    const { warnings } = prefillFromPromotion(fakeRule(), { targetEnvAppSlugs: ['other-app'] });
    expect(warnings.find((w) => w.field === 'scope.appSlug')).toBeTruthy();
  });

  it('warns if webhook connection is not allowed in target env', () => {
    const rule = fakeRule({
      webhooks: [
        {
          id: 'w1',
          outboundConnectionId: 'conn-prod',
          bodyOverride: undefined,
          headerOverrides: {},
        },
      ],
    });
    const { warnings } = prefillFromPromotion(rule, { targetEnvAllowedConnectionIds: ['conn-dev'] });
    expect(warnings.find((w) => w.field.startsWith('webhooks['))).toBeTruthy();
  });
});
