import { appointmentWithinWorkingHours } from './working-hours';
import {
  civilDateInZone,
  isValidIanaTimeZone,
  zonedWeekdayAndMinutes,
} from './zoned-civil-time';

describe('zoned civil time', () => {
  it('accepts IANA zones and rejects garbage', () => {
    expect(isValidIanaTimeZone('Asia/Tehran')).toBe(true);
    expect(isValidIanaTimeZone('Europe/Amsterdam')).toBe(true);
    expect(isValidIanaTimeZone('Not/AZone')).toBe(false);
  });

  it('maps a UTC instant to Tehran wall-clock (no DST)', () => {
    // 2026-08-20 09:45 Asia/Tehran = 06:15 UTC (the production 400 case)
    const instant = new Date('2026-08-20T06:15:00.000Z');
    const zoned = zonedWeekdayAndMinutes(instant, 'Asia/Tehran');
    expect(zoned.jsWeekday).toBe(4); // Thursday
    expect(zoned.minuteOfDay).toBe(9 * 60 + 45);
  });

  it('treats morning Tehran slots as inside 08:00–17:00 hours', () => {
    const start = new Date('2026-08-20T06:15:00.000Z');
    const end = new Date('2026-08-20T06:45:00.000Z');
    expect(
      appointmentWithinWorkingHours(
        start,
        end,
        [{ startMinute: 8 * 60, endMinute: 17 * 60 }],
        'Asia/Tehran',
      ),
    ).toBe(true);
    expect(
      appointmentWithinWorkingHours(
        start,
        end,
        [{ startMinute: 8 * 60, endMinute: 17 * 60 }],
        'UTC',
      ),
    ).toBe(false);
  });
  describe('civilDateInZone', () => {
    it('gives the local civil date, which can differ from the UTC date', () => {
      // 21:30 UTC is already the next day in Tehran (+03:30).
      const instant = new Date('2025-10-11T21:30:00.000Z');
      expect(civilDateInZone(instant, 'UTC')).toBe('2025-10-11');
      expect(civilDateInZone(instant, 'Asia/Tehran')).toBe('2025-10-12');
    });

    it('gives the previous day for zones behind UTC just after midnight', () => {
      const instant = new Date('2025-10-11T02:00:00.000Z');
      expect(civilDateInZone(instant, 'America/New_York')).toBe('2025-10-10');
      expect(civilDateInZone(instant, 'Europe/Amsterdam')).toBe('2025-10-11');
    });

    it('falls back to UTC on an invalid zone rather than throwing', () => {
      // Intl raises RangeError on an unknown zone and this takes a client-supplied string.
      const instant = new Date('2025-10-11T21:30:00.000Z');
      expect(() => civilDateInZone(instant, 'Not/AZone')).not.toThrow();
      expect(civilDateInZone(instant, 'Not/AZone')).toBe('2025-10-11');
      expect(civilDateInZone(instant, '')).toBe('2025-10-11');
    });

    it('zero-pads single-digit months and days', () => {
      expect(civilDateInZone(new Date('2025-01-05T12:00:00.000Z'), 'UTC')).toBe(
        '2025-01-05',
      );
    });
  });
});
