<?php

namespace App\Commands;

use App\Models\Control\TenantRecordModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

/**
 * Batch job (same "loop every active tenant, setTenant() per iteration"
 * shape as SendPreArrivalReminders/SendBirthdayOffers) meant to run once
 * a day via cron/Task Scheduler:
 *   php spark ai:daily-briefing
 *
 * Skips a tenant that has the feature turned off (Settings > AI Features)
 * or already has today's briefing (DailyBriefingService's own
 * idempotency check via ai_daily_briefings.briefing_date's unique key —
 * a second run the same day, or a retry after a partial failure, never
 * regenerates or double-charges for an already-generated day).
 */
class GenerateDailyBriefing extends BaseCommand
{
    protected $group       = 'AI';
    protected $name        = 'ai:daily-briefing';
    protected $description = 'Generates each active tenant\'s AI morning briefing for today, if not already generated.';

    public function run(array $params)
    {
        $tenants = (new TenantRecordModel())->where('status', 'active')->findAll();

        foreach ($tenants as $tenant) {
            $this->generateForTenant($tenant);
        }
    }

    private function generateForTenant(object $tenant): void
    {
        service('tenantContext')->setTenant($tenant);

        if (service('settings')->get('ai.daily_briefing_enabled', '1') !== '1') {
            CLI::write("{$tenant->slug}: daily briefing is turned off, skipping.", 'white');

            return;
        }

        $result = service('dailyBriefingService')->generateForCurrentTenant();

        if (! $result['success']) {
            CLI::error("{$tenant->slug}: failed — {$result['error']}");

            return;
        }

        CLI::write("{$tenant->slug}: briefing ready for {$result['briefing']->briefing_date}.", 'green');
    }
}
