import { spawnSync } from 'child_process';
import * as path from 'path';

const scriptPath = path.resolve(__dirname, '../skills/insure-audit/scripts/index.cjs');

function baseInput(overrides: Record<string, any> = {}) {
  const order = {
    orderNo: 'UT-PLUSC-001',
    productName: '出行无忧 Plus C',
    packageType: 3,
    carPurchaseTime: '2021-05-19',
    createTime: '2026-05-19',
    cardName: '张三',
    cardNumber: '110101199001011234',
    carFrame: 'LS6D3G0Y0NA500002',
    carHost: 0,
    modelName: '长安SUV',
    ...(overrides.order || {}),
  };
  return {
    order,
    idCardOcr: {
      fields: {
        name: '张三',
        idNumber: '110101199001011234',
      },
    },
    vehicleInvoiceOcr: {
      fields: {
        buyerName: '张三',
        vin: 'LS6D3G0Y0NA500002',
        issueDate: order.carPurchaseTime,
        vehicleType: '小型轿车',
        brandModel: '长安牌SUV',
        ...(overrides.vehicleInvoiceOcr?.fields || {}),
      },
    },
    config: {
      maxPurchaseAgeDays: 180,
      ...(overrides.config || {}),
    },
  };
}

function runSkill(input: Record<string, any>) {
  const result = spawnSync(process.execPath, [scriptPath], {
    input: JSON.stringify(input),
    encoding: 'utf8',
  });
  if (result.status !== 0) {
    throw new Error(result.stderr || result.stdout);
  }
  return JSON.parse(result.stdout);
}

function findRule(result: any, id: string) {
  return result.rules.find((item: any) => item.id === id);
}

describe('insure-audit Plus C vehicle age rule', () => {
  it('rejects Plus C when vehicle age is more than 5 years', () => {
    const result = runSkill(baseInput({
      order: { carPurchaseTime: '2021-05-18' },
    }));

    expect(result.status).toBe('REJECT');
    expect(result.reason).toContain('PlusC车龄限制');
    expect(findRule(result, 'R7_PLUS_C_VEHICLE_AGE')).toEqual(expect.objectContaining({
      status: 'REJECT',
      reason: 'Plus C/代步权益产品不允许车龄超过5年的车辆购买',
    }));
    expect(findRule(result, 'R3_PURCHASE_AGE')).toEqual(expect.objectContaining({
      status: 'PASS',
    }));
  });

  it('allows Plus C on the exact 5 year anniversary', () => {
    const result = runSkill(baseInput());

    expect(result.status).toBe('PASS');
    expect(result.reason).toBe('7项规则均通过');
    expect(findRule(result, 'R7_PLUS_C_VEHICLE_AGE')).toEqual(expect.objectContaining({
      status: 'PASS',
      reason: 'Plus C/代步权益产品车龄未超过5年',
    }));
  });

  it('does not apply the 5 year Plus C limit to non-Plus C products', () => {
    const result = runSkill(baseInput({
      order: {
        productName: '出行无忧 Plus A',
        packageType: 1,
        carPurchaseTime: '2021-05-18',
      },
      vehicleInvoiceOcr: {
        fields: {
          issueDate: '2026-05-01',
        },
      },
    }));

    expect(result.status).toBe('PASS');
    expect(findRule(result, 'R7_PLUS_C_VEHICLE_AGE')).toEqual(expect.objectContaining({
      status: 'PASS',
      reason: '非Plus C/代步权益产品，不适用5年车龄限制',
    }));
  });

  it('sends Plus C to manual review when vehicle age date is missing', () => {
    const input = baseInput({
      order: { carPurchaseTime: '' },
      vehicleInvoiceOcr: {
        fields: {
          issueDate: '',
        },
      },
    });
    const result = runSkill(input);

    expect(result.status).toBe('MANUAL_REVIEW');
    expect(findRule(result, 'R7_PLUS_C_VEHICLE_AGE')).toEqual(expect.objectContaining({
      status: 'MANUAL_REVIEW',
      reason: 'Plus C/代步权益产品缺少车龄起算日期，无法判断是否超过5年',
    }));
  });
});
