import { describe, expect, it } from 'vitest';
import {
  quotaPolicyFromForm,
  quotaPolicySummary,
  quotaPolicyToForm,
  rateLimitPolicyFromForm,
  rateLimitPolicySummary,
  rateLimitPolicyToForm,
} from './UserGroupPolicyEditors';

describe('user group policy editors', () => {
  it('round-trips canonical rate limits and preserves unknown top-level fields', () => {
    const source = {
      strategy: 'strict',
      rules: [
        { metric: 'rpm' as const, limit: 60, windowSeconds: 60 },
        { metric: 'concurrent' as const, limit: 3, leaseTtlSeconds: 120 },
      ],
    };
    const form = rateLimitPolicyToForm(source);

    expect(rateLimitPolicyFromForm(form.rules, form.extra)).toEqual(source);
    expect(rateLimitPolicySummary(source)).toEqual(['RPM 60', '并发 3']);
  });

  it('rejects duplicate rate-limit metrics', () => {
    const form = rateLimitPolicyToForm({
      rules: [
        { metric: 'rpm', limit: 60 },
        { metric: 'rpm', limit: 120 },
      ],
    });

    expect(() => rateLimitPolicyFromForm(form.rules, form.extra)).toThrow('不能重复');
  });

  it('normalizes zero queues and round-trips queue wait settings with extensions', () => {
    const source = {
      rules: [
        { metric: 'queue_size' as const, limit: 8, maxWaitSeconds: 75, source: 'custom' },
      ],
    };
    const form = rateLimitPolicyToForm(source);
    expect(rateLimitPolicyFromForm(form.rules, form.extra)).toEqual(source);
    expect(rateLimitPolicySummary(source)).toEqual(['排队 8 / 75秒']);

    form.rules[0].limit = '0';
    expect(rateLimitPolicyFromForm(form.rules, form.extra)).toBeUndefined();
  });

  it('defaults queue wait to 600 seconds and validates upper bounds', () => {
    const form = rateLimitPolicyToForm({
      rules: [{ metric: 'queue_size', limit: 2 }],
    });
    expect(rateLimitPolicyFromForm(form.rules, form.extra)).toEqual({
      rules: [{ metric: 'queue_size', limit: 2, maxWaitSeconds: 600 }],
    });
    form.rules[0].maxWaitSeconds = '3601';
    expect(() => rateLimitPolicyFromForm(form.rules, form.extra)).toThrow('1–3600');
  });

  it('round-trips quota values without changing their types', () => {
    const source = {
      monthlyResource: 10000,
      plan: 'vip',
      enabled: true,
      dimensions: { image: 20 },
    };
    const form = quotaPolicyToForm(source);

    expect(quotaPolicyFromForm(form)).toEqual(source);
    expect(quotaPolicySummary(source)).toEqual([
      'monthlyResource 10000',
      'plan vip',
      'enabled true',
    ]);
  });
});
