<?php

namespace App\Console\Commands;

use App\Models\Company;
use App\Models\CompanySubscription;
use Illuminate\Console\Command;

/**
 * The automated half of the status lifecycle — the other half is the root
 * admin's manual Suspend/Reactivate buttons in the SaaS control panel.
 * Two jobs, run together since the second depends on the first:
 *
 *   1. Mark any subscription whose expires_at has passed as 'expired'.
 *   2. Recompute every non-suspended company's status from whichever
 *      subscription is actually in force — pending if it hasn't started
 *      yet, expired if step 1 just closed it out, active otherwise.
 *
 * Suspended companies are skipped entirely: that's a manual override, and
 * only the root admin's Reactivate button ends it.
 */
class SyncCompanyStatuses extends Command
{
    protected $signature = 'companies:sync-status';

    protected $description = 'Expire past-due subscriptions and recompute every non-suspended company\'s status from its subscription dates';

    public function handle(): int
    {
        $expiredCount = CompanySubscription::where('status', 'active')
            ->whereNotNull('expires_at')
            ->where('expires_at', '<', now())
            ->update(['status' => 'expired']);

        $companies = Company::where('status', '!=', 'suspended')->get();

        $changed = 0;

        foreach ($companies as $company) {
            $before = $company->status;
            $company->recomputeStatus();

            if ($company->status !== $before) {
                $changed++;
                $this->info("{$company->name}: {$before} -> {$company->status}");
            }
        }

        $this->info("Expired {$expiredCount} subscription(s); {$changed} of {$companies->count()} companies changed status.");

        return self::SUCCESS;
    }
}
