<?php

use classes\invoicing_period_utils;

app_require('classes/invoicing_period_utils.php');

it('normalizes a valid invoicing date range to full-day timestamps', function (): void {
    $range = invoicing_period_utils::normalizeDateRange('2026-03-01', '2026-03-31');

    expect($range)->toBe([
        'dateFrom' => '2026-03-01 00:00:00',
        'dateTo' => '2026-03-31 23:59:59',
    ]);
});

it('rejects invalid date formats', function (): void {
    invoicing_period_utils::normalizeDateRange('2026/03/01', '2026-03-31');
})->throws(InvalidArgumentException::class, 'Invalid date format. Expected: Y-m-d Got: 2026/03/01');

it('rejects descending date ranges', function (): void {
    invoicing_period_utils::normalizeDateRange('2026-04-01', '2026-03-31');
})->throws(InvalidArgumentException::class, 'Invalid date range. dateFrom must be before or equal to dateTo');

it('finds duplicate orders regardless of original input order', function (): void {
    $input = [
        'ABC12345' => [
            ['id' => 3, 'created_at' => '2026-03-03 02:00:00'],
            ['id' => 1, 'created_at' => '2026-03-01 12:00:00'],
            ['id' => 2, 'created_at' => '2026-03-02 07:00:00'],
        ],
        'NON_DUP' => [
            ['id' => 10, 'created_at' => '2026-03-01 00:00:00'],
            ['id' => 11, 'created_at' => '2026-03-03 00:00:01'],
        ],
    ];

    $duplicates = invoicing_period_utils::filterPossibleDuplicates($input, 86400);

    expect(array_keys($duplicates))->toBe(['ABC12345']);
    expect(array_column($duplicates['ABC12345'], 'id'))->toBe([1, 2, 3]);
});

