<?php

declare(strict_types=1);

use App\Models\Workspace;
use App\Models\WorkspaceSubscription;
use App\Services\Entitlements\WorkspaceCommercialLifecycleResolver;
use App\Services\Entitlements\WorkspaceSubscriptionResolver;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('summarizes a trial subscription as subscription-backed truth', function (): void {
    $workspace = Workspace::factory()->create();
    $trialEndsAt = now()->addDays(14)->startOfMinute();

    WorkspaceSubscription::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'state' => 'trial',
        'trial_ends_at' => $trialEndsAt,
        'status_reason' => 'Trial access for onboarding.',
    ]);

    $summary = app(WorkspaceSubscriptionResolver::class)->summary($workspace);

    expect($summary)
        ->toMatchArray([
            'workspace_id' => (int) $workspace->getKey(),
            'subscription_present' => true,
            'state' => 'trial',
            'source' => 'workspace_subscription',
            'fallback_status' => false,
            'derived_lifecycle_state' => WorkspaceCommercialLifecycleResolver::STATE_TRIAL,
            'needs_review' => false,
            'status_reason' => 'Trial access for onboarding.',
            'key_date_label' => 'Trial ends',
        ])
        ->and($summary['key_date']?->toDateTimeString())
        ->toBe($trialEndsAt->toDateTimeString());
});

it('marks stale cancel-at-period-end subscriptions for explicit review', function (): void {
    $workspace = Workspace::factory()->create();
    $periodStartsAt = now()->subDays(30)->startOfMinute();
    $periodEndsAt = now()->subDay()->startOfMinute();

    WorkspaceSubscription::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'state' => 'cancel_at_period_end',
        'current_period_starts_at' => $periodStartsAt,
        'current_period_ends_at' => $periodEndsAt,
        'status_reason' => 'Cancellation takes effect at period end.',
    ]);

    $summary = app(WorkspaceSubscriptionResolver::class)->summary($workspace);

    expect($summary)
        ->toMatchArray([
            'workspace_id' => (int) $workspace->getKey(),
            'subscription_present' => true,
            'state' => 'cancel_at_period_end',
            'source' => 'workspace_subscription',
            'fallback_status' => false,
            'derived_lifecycle_state' => WorkspaceCommercialLifecycleResolver::STATE_ACTIVE_PAID,
            'needs_review' => true,
            'status_reason' => 'Cancellation takes effect at period end.',
            'key_date_label' => 'Current period ends',
        ])
        ->and($summary['key_date']?->toDateTimeString())
        ->toBe($periodEndsAt->toDateTimeString());
});
