<?php

namespace Modules\VetClinic\Console;

use App\Business;
use Illuminate\Console\Command;
use Modules\VetClinic\Entities\VcControlledDailySeal;

/**
 * Nightly job: seal every business-day older than today that doesn't yet
 * have a seal. Idempotent — re-running on the same day is a no-op.
 *
 * Schedule in App\Console\Kernel (or via cron) at 00:05:
 *   $schedule->command('vc:controlled:seal-day')->dailyAt('00:05');
 */
class VcSealControlledRegister extends Command
{
    protected $signature = 'vc:controlled:seal-day {--business= : Only seal this business id}';
    protected $description = 'Seal yesterday and any earlier unsealed days of the controlled-drug register (SHA-256 chain).';

    public function handle(): int
    {
        $query = Business::query();
        if ($this->option('business')) {
            $query->where('id', (int) $this->option('business'));
        }

        $total = 0;
        foreach ($query->pluck('id') as $bizId) {
            $sealed = VcControlledDailySeal::sealOutstanding((int) $bizId);
            foreach ($sealed as $s) {
                $this->line(sprintf('biz %d · %s · %d rows · %s', $bizId, $s['date'], $s['count'], substr($s['hash'], 0, 12) . '…'));
                $total++;
            }
        }
        $this->info("Sealed {$total} day(s).");
        return self::SUCCESS;
    }
}
