<?php

namespace App\Console\Commands;

use App\Mail\CallExpiredMail;
use App\Mail\CallExpiringMail;
use App\Models\Call;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class ProcessCallExpiry extends Command
{
    protected $signature   = 'calls:process-expiry';
    protected $description = 'Send expiry warning and expired notification emails for calls';

    public function handle(): int
    {
        $warningDays = (int) timebank_config('calls.expiry_warning_days', 7);

        // Calls expiring in exactly $warningDays days
        $warnDate = now()->addDays($warningDays)->toDateString();
        $expiringSoon = Call::with(['callable', 'tag'])
            ->whereNotNull('till')
            ->whereDate('till', $warnDate)
            ->where('is_suppressed', false)
            ->where('is_paused', false)
            ->whereNull('deleted_at')
            ->get();

        $warnCount = 0;
        foreach ($expiringSoon as $call) {
            $callable = $call->callable;
            if (!$callable || !$callable->email) {
                continue;
            }
            $settings = $callable->message_settings()->first();
            if ($settings && !($settings->call_expiry ?? true)) {
                continue;
            }
            Mail::to($callable->email)->queue(
                new CallExpiringMail($call, $callable, class_basename($callable), $warningDays)
            );
            $warnCount++;
        }

        // Calls that expired yesterday
        $yesterday = now()->subDay()->toDateString();
        $expired = Call::with(['callable', 'tag'])
            ->whereNotNull('till')
            ->whereDate('till', $yesterday)
            ->where('is_suppressed', false)
            ->where('is_paused', false)
            ->whereNull('deleted_at')
            ->get();

        $expiredCount = 0;
        foreach ($expired as $call) {
            $callable = $call->callable;
            if (!$callable || !$callable->email) {
                continue;
            }
            $settings = $callable->message_settings()->first();
            if ($settings && !($settings->call_expiry ?? true)) {
                continue;
            }
            Mail::to($callable->email)->queue(
                new CallExpiredMail($call, $callable, class_basename($callable))
            );
            $expiredCount++;
        }

        $this->info("Call expiry processed: {$warnCount} expiry warnings queued, {$expiredCount} expiry notifications queued.");

        return 0;
    }
}
