<?php

namespace App\Domains\Billing\Actions;

use App\Domains\Billing\Models\Subscription;
use App\Domains\Tenancy\Models\Tenant;

class SyncTenantLifecycleAction
{
    public function execute(Tenant $tenant): string
    {
        /** @var Subscription|null $subscription */
        $subscription = $tenant->subscriptions()->latest('created_at')->first();
        $subscriptionExpired = $subscription?->ends_at && now()->greaterThanOrEqualTo($subscription->ends_at);

        $status = match (true) {
            $subscriptionExpired => 'suspended',
            $subscription?->status === 'cancelled' || $subscription?->cancelled_at !== null => 'cancelled',
            in_array($subscription?->status, ['past_due', 'failed'], true) => 'past_due',
            $tenant->trial_ends_at && now()->lt($tenant->trial_ends_at) => 'trial',
            in_array($subscription?->status, ['active', 'paid', 'succeeded'], true) => 'active',
            $tenant->trial_ends_at && now()->gte($tenant->trial_ends_at) => 'past_due',
            default => $tenant->status,
        };

        $tenant->update([
            'status' => $status,
        ]);

        return $status;
    }
}
