jest.mock('../../server/lib/postgres', () => ({
  get: jest.fn(),
  run: jest.fn(),
}));

const { get, run } = require('../../server/lib/postgres');
const { syncRevenueCatCustomerInfo } = require('../../server/lib/billing');

describe('server billing timestamp normalization', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    run.mockResolvedValue({ lastId: null, changes: 1, rows: [] });
  });

  it('upserts ISO timestamps when postgres returns Date objects', async () => {
    get.mockResolvedValueOnce({
      userId: 'usr_mnjcdwpo_ax9lf68b',
      plan: 'free',
      provider: 'revenuecat',
      cycleStartedAt: new Date('2026-04-01T00:00:00.000Z'),
      cycleEndsAt: new Date('2026-05-01T00:00:00.000Z'),
      monthlyAllowance: 15,
      usedThisCycle: 0,
      topupBalance: 0,
      renewsAt: null,
      updatedAt: new Date('2026-04-02T12:00:00.000Z'),
    });

    await syncRevenueCatCustomerInfo(
      {},
      'usr_mnjcdwpo_ax9lf68b',
      { entitlements: { active: {} }, nonSubscriptions: {} },
      { source: 'topup_purchase' },
    );

    const upsertCall = run.mock.calls.find(([, sql]) => typeof sql === 'string' && sql.includes('INSERT INTO billing_accounts'));
    expect(upsertCall).toBeTruthy();

    const params = upsertCall[2];
    expect(params[3]).toBe('2026-04-01T00:00:00.000Z');
    expect(params[4]).toBe('2026-05-01T00:00:00.000Z');
    expect(params[3]).not.toContain('Coordinated Universal Time');
    expect(params[4]).not.toContain('Coordinated Universal Time');
  });
});
