import assert from 'node:assert/strict';
import { test } from 'node:test';
import { BadRequestException } from '@nestjs/common';
import { validateFitPresetRules } from './fit.service';

const rule = (
  fieldKey: string,
  applicability: 'KS' | 'CP' | 'BOTH',
  overrides: Partial<{
    adjustmentType: 'INCHES' | 'PERCENTAGE';
    adjustmentValue: string;
    isActive: boolean;
  }> = {},
) => ({
  fieldKey,
  applicability,
  adjustmentType: overrides.adjustmentType ?? 'INCHES' as const,
  adjustmentValue: overrides.adjustmentValue ?? '2',
  isActive: overrides.isActive ?? true,
});

test('fit rule validation accepts eligible KS and CP fields in a BOTH preset', () => {
  assert.doesNotThrow(() =>
    validateFitPresetRules('BOTH', [
      rule('kCh', 'KS'),
      rule('cpPW', 'CP', { adjustmentType: 'PERCENTAGE', adjustmentValue: '10' }),
    ]),
  );
});

test('fit rule validation rejects non-fit and user-entered field names', () => {
  for (const fieldKey of ['remarks', 'kamizQty', 'frontPocket', 'Chest']) {
    assert.throws(
      () => validateFitPresetRules('KS', [rule(fieldKey, 'KS')]),
      BadRequestException,
    );
  }
});

test('fit rule validation rejects family and preset scope mismatches', () => {
  assert.throws(
    () => validateFitPresetRules('CP', [rule('kCh', 'KS')]),
    /outside the CP preset scope/,
  );
  assert.throws(
    () => validateFitPresetRules('BOTH', [rule('kCh', 'CP')]),
    /not valid for CP/,
  );
  assert.throws(
    () => validateFitPresetRules('BOTH', [rule('kCh', 'BOTH')]),
    /exact KS or CP family scope/,
  );
});

test('fit rule validation rejects duplicate active field rules', () => {
  assert.throws(
    () => validateFitPresetRules('KS', [rule('kCh', 'KS'), rule('kCh', 'KS')]),
    /one adjustment/i,
  );
});

test('fit rule validation rejects inactive duplicate combinations before the database constraint', () => {
  assert.throws(
    () =>
      validateFitPresetRules('KS', [
        rule('kCh', 'KS', { isActive: false }),
        rule('kCh', 'KS', { isActive: false }),
      ]),
    (error: unknown) =>
      error instanceof BadRequestException && /one adjustment/i.test(error.message),
  );
});

test('fit rule validation keeps Regular zero-adjustment', () => {
  assert.doesNotThrow(() =>
    validateFitPresetRules('BOTH', [], { name: 'Regular', code: 'REGULAR' }),
  );
  assert.throws(
    () =>
      validateFitPresetRules(
        'BOTH',
        [rule('kCh', 'KS')],
        { name: 'Regular', code: 'REGULAR' },
      ),
    /zero-adjustment/,
  );
});