<?php

namespace Tests\Unit;

use App\Models\Coupon;
use App\Models\Package;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CouponTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_evaluates_active_state(): void
    {
        $coupon = Coupon::factory()->create([
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addDay(),
            'usage_limit' => 1,
            'redemptions_count' => 0,
        ]);

        $this->assertTrue($coupon->isCurrentlyActive());

        $coupon->update(['redemptions_count' => 1]);

        $this->assertFalse($coupon->refresh()->isCurrentlyActive());

        $coupon->update([
            'usage_limit' => null,
            'starts_at' => now()->addDay(),
            'redemptions_count' => 0,
        ]);

        $this->assertFalse($coupon->fresh()->isCurrentlyActive());
    }

    public function test_it_checks_package_applicability(): void
    {
        $coupon = Coupon::factory()->create();
        $packageA = Package::factory()->create();
        $packageB = Package::factory()->create();

        $this->assertTrue($coupon->appliesToPackage($packageA));

        $coupon->packages()->sync([$packageA->getKey()]);

        $this->assertTrue($coupon->fresh()->appliesToPackage($packageA));
        $this->assertFalse($coupon->appliesToPackage($packageB));
    }

    public function test_remaining_usage_calculation(): void
    {
        $coupon = Coupon::factory()->create([
            'usage_limit' => 10,
            'per_customer_limit' => 2,
            'redemptions_count' => 4,
        ]);

        $this->assertSame(6, $coupon->remainingUsages());
        $this->assertSame(2, $coupon->remainingUsages(0));
        $this->assertSame(1, $coupon->remainingUsages(1));
    }
}
