<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Tests\Marketing;

use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Model\Promo;
use CpCreation\VitiCore\Marketing\Model\AbandonedCartConfiguration;
use CpCreation\VitiCore\Marketing\Model\AbandonedCartReminder;
use CpCreation\VitiCore\Marketing\Model\AbandonedCartRule;
use PHPUnit\Framework\TestCase;

final class AbandonedCartReminderTest extends TestCase
{
    public function testLifecycleFromSchedulingToRecovery(): void
    {
        $now = new \DateTimeImmutable('2026-07-23 12:00:00');
        $reminder = $this->createReminder($now);

        self::assertTrue($reminder->isScheduled());
        self::assertFalse($reminder->isUsableAt($now));

        $reminder->markSent($now);

        self::assertSame(AbandonedCartReminder::STATUS_SENT, $reminder->getStatus());
        self::assertTrue($reminder->isUsableAt($now));

        $reminder->markRecovered($now->modify('+1 hour'));

        self::assertSame(AbandonedCartReminder::STATUS_RECOVERED, $reminder->getStatus());
        self::assertNotNull($reminder->getRecoveredAt());
    }

    public function testCancelDisablesGeneratedCoupon(): void
    {
        $now = new \DateTimeImmutable();
        $reminder = $this->createReminder($now);
        $promo = $reminder->getPromo();
        $promo?->setTitle('PANIER-REMPLACE');
        $reminder->getCart()->setPromoCodeInput($promo?->getTitle());

        $reminder->cancel();

        self::assertSame(AbandonedCartReminder::STATUS_CANCELED, $reminder->getStatus());
        self::assertTrue($promo?->isDisabled());
        self::assertNull($reminder->getCart()->getPromoCodeInput());
        self::assertNull($reminder->getCart()->getPromoCodeStatus());
        self::assertNull($reminder->getCart()->getPromoCodeMessageKey());
    }

    private function createReminder(\DateTimeImmutable $now): AbandonedCartReminder
    {
        return new AbandonedCartReminder(
            cart: new Cart(),
            rule: new AbandonedCartRule(new AbandonedCartConfiguration()),
            promo: new Promo(),
            recipientEmail: 'client@example.com',
            tokenHash: hash('sha256', 'token'),
            scheduledAt: $now,
            expiresAt: $now->modify('+7 days'),
        );
    }
}
