<?php

namespace Tests\Unit;

use App\Services\MonthlyPoScheduler;
use PHPUnit\Framework\TestCase;

class MonthlyPoSchedulerTest extends TestCase
{
    public function testItMovesAnOrderToTheNextMonthWhenTheRequestedMonthIsFull(): void
    {
        $schedule = MonthlyPoScheduler::allocate(
            4,
            10,
            '2026-07-19',
            static fn (string $month): int => $month === '2026-07-01' ? 10 : 0
        );

        $this->assertSame([
            ['scheduled_month' => '2026-08-01', 'quantity' => 4],
        ], $schedule);
    }

    public function testItSplitsOneCustomersOrderAcrossMonthlyCapacity(): void
    {
        $schedule = MonthlyPoScheduler::allocate(
            15,
            10,
            '2026-07-19',
            static fn (string $month): int => $month === '2026-07-01' ? 7 : 0
        );

        $this->assertSame([
            ['scheduled_month' => '2026-07-01', 'quantity' => 3],
            ['scheduled_month' => '2026-08-01', 'quantity' => 10],
            ['scheduled_month' => '2026-09-01', 'quantity' => 2],
        ], $schedule);
    }

    public function testUnlimitedCapacityKeepsTheWholeOrderInRequestedMonth(): void
    {
        $schedule = MonthlyPoScheduler::allocate(
            15,
            0,
            '2026-07-19',
            static fn (): int => 999
        );

        $this->assertSame([
            ['scheduled_month' => '2026-07-01', 'quantity' => 15],
        ], $schedule);
    }

    public function testItDistributesOrderItemsAccordingToTheMonthlyBatches(): void
    {
        $batches = MonthlyPoScheduler::distributeItems(
            [
                ['id_product' => 12, 'qty' => 3],
                ['id_product' => null, 'qty' => 2],
                ['id_product' => 13, 'qty' => 3],
            ],
            [
                ['scheduled_month' => '2026-07-01', 'quantity' => 4],
                ['scheduled_month' => '2026-08-01', 'quantity' => 4],
            ]
        );

        $this->assertSame([
            [12, '2026-07-01', 3],
            [null, '2026-07-01', 1],
            [null, '2026-08-01', 1],
            [13, '2026-08-01', 3],
        ], array_map(static fn (array $batch): array => [
            $batch['item']['id_product'],
            $batch['scheduled_month'],
            $batch['quantity'],
        ], $batches));
    }
}
