<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Enums\JobStatus;
use App\Models\Job;
use App\Services\OwnerEarningsService;
use Illuminate\Console\Command;

class GenerateOwnerEarnings extends Command
{
    /**
     * The name and signature of the console command.
     *
     * You can later add options/flags here if needed (e.g. --dry-run).
     */
    protected $signature = 'owners:generate-earnings';

    /**
     * The console command description.
     */
    protected $description = 'Generate owner earnings for completed consignment jobs (car returned, no damage or extra charges).';

    public function __construct(
        protected OwnerEarningsService $service,
    ) {
        parent::__construct();
    }

    public function handle(): int
    {
        // Jobs that:
        // - are consignment vehicles
        // - have finished (end_at in the past)
        // - have their hold/bond Released (no capture → no extra charges/damage)
        // - have not yet had owner earnings generated
        $query = Job::query()
            ->whereNull('owner_earnings_generated_at')
            ->whereHas('vehicle', fn ($q) => $q->where('ownership_type', 'consignment'))
            ->where('end_at', '<=', now())
            ->where('status', JobStatus::Released->value);

        $totalMatching = (clone $query)->count();

        if ($totalMatching === 0) {
            $this->info('No eligible jobs found for owner earnings.');
            return self::SUCCESS;
        }

        $this->info("Found {$totalMatching} eligible job(s). Generating owner earnings...");

        $processed = 0;

        $query->chunkById(50, function ($jobs) use (&$processed): void {
            /** @var \App\Models\Job $job */
            foreach ($jobs as $job) {
                // Create the ledger entries for this job
                $this->service->createLedgerEntriesForJob($job);

                // Mark that earnings have been generated so we don't process it again
                $job->owner_earnings_generated_at = now();
                $job->save();

                $processed++;
            }
        });

        $this->info("Processed {$processed} job(s).");

        return self::SUCCESS;
    }
}
