<?php

use App\Enums\SubscriptionPlan;
use App\Enums\SubscriptionStatus;
use App\Models\Subscription;

it('casts plan, order_status, dates and booleans to their expected types', function () {
    $subscription = Subscription::factory()->premium()->confirmed()->create();

    expect($subscription->plan)->toBe(SubscriptionPlan::Premium)
        ->and($subscription->order_status)->toBe(SubscriptionStatus::Confirmed)
        ->and($subscription->plan_price)->toBe('600.00')
        ->and($subscription->start_date)->toBeInstanceOf(Carbon\CarbonInterface::class)
        ->and($subscription->terms_agreed)->toBeTrue()
        ->and($subscription->promo_emails)->toBeBool();
});

it('never derives plan price from anything but the enum', function () {
    foreach (SubscriptionPlan::cases() as $plan) {
        $subscription = Subscription::factory()->create([
            'plan' => $plan,
            'plan_price' => $plan->price(),
        ]);

        expect((float) $subscription->plan_price)->toBe($plan->price());
    }
});

it('enforces the phone, plan and start_date dedupe unique constraint', function () {
    $attributes = Subscription::factory()->make([
        'phone' => '9876543210',
        'plan' => SubscriptionPlan::Basic,
        'start_date' => '2026-09-01',
    ])->toArray();

    Subscription::query()->create($attributes);

    $attributes['order_id'] = 'PVF-SUB-'.strtoupper(Illuminate\Support\Str::random(8));

    expect(fn () => Subscription::query()->create($attributes))
        ->toThrow(Illuminate\Database\QueryException::class);
});
