<?php

namespace App\Console\Commands;

use App\Models\Lead;
use App\Http\Controllers\Controller;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class AutoApproveHeldLeads extends Command
{
    protected $signature = 'leads:auto-approve';

    protected $description = 'Approve held leads once they have been on hold longer than the configured window';

    public function handle(): int
    {
        $hours = site_int('leads_auto_approve_hours', 0);

        if ($hours <= 0) {
            $this->info('Auto-approval disabled (leads_auto_approve_hours is 0).');

            return self::SUCCESS;
        }

        $cutoff = now()->subHours($hours);

        $leads = Lead::query()
            ->where('status', 'held')
            ->where('created_at', '<=', $cutoff)
            ->get();

        foreach ($leads as $lead) {
            DB::transaction(function () use ($lead, $hours) {
                app(Controller::class)->awardLeadPoints($lead);

                $lead->fill([
                    'status' => 'approved',
                    'admin_note' => "Auto-approved after {$hours}h hold window.",
                    'reviewed_at' => now(),
                ])->save();
            });
        }

        $this->info("Auto-approved {$leads->count()} held lead(s) older than {$hours}h.");

        return self::SUCCESS;
    }
}
