import { describe, it, expect } from 'vitest';
import {
  validatePeId,
  validateHeaderForCategory,
  normalizeIndianMobile,
  isWithinPromotionalQuietHours,
  validateSmsDltDispatch,
} from '../../apps/gateway/src/compliance/dlt-validator.js';
import type { DltConfigModel } from '@zyphon/config-schema';

const baseDlt: DltConfigModel = {
  pe_id: '1100123456789012345',
  headers: [
    { id: 'h1', header: 'ACMEIN', category: 'transactional' },
    { id: 'h2', header: '654321', category: 'promotional' },
  ],
  quiet_hours: {
    enabled: true,
    start: '21:00',
    end: '09:00',
    timezone: 'Asia/Kolkata',
  },
  default_country_code: '91',
};

describe('DLT validator', () => {
  it('validates PE ID as 19 digits', () => {
    expect(validatePeId('1100123456789012345').ok).toBe(true);
    expect(validatePeId('123').ok).toBe(false);
  });

  it('validates header rules by category', () => {
    expect(validateHeaderForCategory('ACMEIN', 'transactional').ok).toBe(true);
    expect(validateHeaderForCategory('654321', 'promotional').ok).toBe(true);
    expect(validateHeaderForCategory('ACMEPR', 'promotional').ok).toBe(false);
  });

  it('normalizes Indian mobile numbers', () => {
    expect(normalizeIndianMobile('9876543210', '91')).toBe('+919876543210');
    expect(normalizeIndianMobile('+919876543210', '91')).toBe('+919876543210');
  });

  it('detects promotional quiet hours in IST', () => {
    const lateIst = new Date('2026-10-14T17:00:00.000Z'); // 22:30 IST
    expect(isWithinPromotionalQuietHours(lateIst, baseDlt)).toBe(true);
    const middayIst = new Date('2026-10-14T06:30:00.000Z'); // 12:00 IST
    expect(isWithinPromotionalQuietHours(middayIst, baseDlt)).toBe(false);
  });

  it('blocks suppressed recipients', () => {
    const msg = {
      message_id: 'm1',
      request_id: 'r1',
      application_id: 'app',
      channel: 'sms' as const,
      recipient: '+919876543210',
      content: { type: 'text' as const, body: 'hello', template: '1107161234567890123' },
      metadata: { dlt_header: 'ACMEIN', dlt_category: 'transactional' },
      created_at: Date.now(),
    };
    const result = validateSmsDltDispatch(msg, {
      dlt: baseDlt,
      suppressions: ['+919876543210'],
    });
    expect(result.ok).toBe(false);
    if (!result.ok) expect(result.code).toBe('BLOCKED');
  });
});
