import { TestBed } from '@angular/core/testing';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { CheckoutCountdownService } from './checkout-countdown.service';

describe('CheckoutCountdownService', () => {
  let service: CheckoutCountdownService;

  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-08-27T12:00:00.000Z'));
    TestBed.configureTestingModule({ providers: [CheckoutCountdownService] });
    service = TestBed.inject(CheckoutCountdownService);
  });

  afterEach(() => {
    service.clear();
    vi.useRealTimers();
  });

  it('counts down from the checkout server timing without depending on the client clock', () => {
    service.synchronize({
      expires_at: '2026-08-27T15:10:00.000Z',
      expires_in_seconds: 600,
      server_time: '2026-08-27T15:00:00.000Z',
    });

    expect(service.remainingSeconds()).toBe(600);

    vi.advanceTimersByTime(1_000);

    expect(service.remainingSeconds()).toBe(599);
  });

  it('recalculates against the deadline after a delayed browser interval', () => {
    service.synchronize({
      expires_at: null,
      expires_in_seconds: 10,
      server_time: '2026-08-27T15:00:00.000Z',
    });

    vi.setSystemTime(new Date('2026-08-27T12:00:07.000Z'));
    vi.advanceTimersByTime(1_000);

    expect(service.remainingSeconds()).toBe(2);
  });

  it('clears the countdown when checkout has no expiration', () => {
    service.synchronize({
      expires_at: null,
      expires_in_seconds: null,
      server_time: '2026-08-27T15:00:00.000Z',
    });

    expect(service.remainingSeconds()).toBeNull();
  });

  it('keeps the active countdown when a partial checkout response omits timing fields', () => {
    service.synchronize({
      expires_at: null,
      expires_in_seconds: 10,
      server_time: '2026-08-27T15:00:00.000Z',
    });

    service.synchronize({});

    expect(service.remainingSeconds()).toBe(10);
  });
});
