<?php

namespace App\Console\Commands;

use App\Mail\ChequeMaturityReminderMail;
use App\Models\Lookups\PaymentMethod;
use App\Models\Lookups\Status;
use App\Models\Sales\Transaction;
use App\Notifications\WhatsApp\WhatsAppGateway;
use App\Services\CurrentContext;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class SendChequeReminders extends Command
{
    protected $signature = 'cheques:send-reminders';

    protected $description = 'Email customers + internal accounts mailbox the day before a cheque\'s maturity date.';

    public function handle(WhatsAppGateway $whatsapp, CurrentContext $context): int
    {
        // Deliberate cross-tenant sweep, unchanged from the source app (see
        // docs/migration-plan.md Decisions Log — this command matches cheques
        // across all tenants against a single PaymentMethod/Status lookup id,
        // which is only correct if those lookup rows share ids across tenants;
        // that's a pre-existing characteristic being preserved as-is, not
        // introduced here).
        return $context->runWithoutTenant(fn () => $this->sweep($whatsapp));
    }

    private function sweep(WhatsAppGateway $whatsapp): int
    {
        $tomorrow = now()->addDay()->toDateString();

        $methodId = PaymentMethod::idOf(PaymentMethod::CHEQUE);
        $pendingStatusId = Status::idOf(Status::CTX_TRANSACTION, Status::PENDING);

        $due = Transaction::query()
            ->where('payment_method_id', $methodId)
            ->where('status_id', $pendingStatusId)
            ->whereDate('cheque_date', $tomorrow)
            ->whereNull('cheque_reminder_sent_at')
            ->with(['customer', 'claims.invoice'])
            ->get();

        $this->info("Found {$due->count()} cheque(s) maturing tomorrow.");

        $systemEmail = config('mail.from.address');

        foreach ($due as $txn) {
            try {
                $customer = $txn->customer;
                if ($customer?->email) {
                    Mail::to($customer->email)
                        ->cc(array_filter([$systemEmail]))
                        ->send(new ChequeMaturityReminderMail($txn));
                }

                if ($customer?->phone && config('services.whatsapp.enabled', false)) {
                    $message = sprintf(
                        'Reminder: Cheque %s for Rs. %s is due tomorrow (%s). — Vellix Point',
                        $txn->cheque_number,
                        number_format((float) $txn->amount, 2),
                        optional($txn->cheque_date)->format('d M Y'),
                    );
                    $whatsapp->send($customer->phone, $message);
                }

                $txn->update(['cheque_reminder_sent_at' => now()]);
            } catch (\Throwable $e) {
                Log::error('cheque_reminder.failed', [
                    'transaction_id' => $txn->id,
                    'message' => $e->getMessage(),
                ]);
            }
        }

        return self::SUCCESS;
    }
}
