<?php

namespace App\Console\Commands;

use App\Domain\Financial\Models\Invoice;
use App\Domain\Financial\Models\Payment;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ReconcileFinancials extends Command
{
    protected $signature = 'financials:reconcile {--fix : Auto-fix discrepancies}';
    protected $description = 'Check invoice paid_amount matches sum of confirmed payments';

    public function handle(): int
    {
        $fix = $this->option('fix');
        $discrepancies = 0;

        $invoices = Invoice::whereIn('status', ['partially_paid', 'paid', 'overdue', 'sent'])
            ->get();

        foreach ($invoices as $invoice) {
            $actualPaid = Payment::where('invoice_id', $invoice->id)
                ->where('status', 'confirmed')
                ->sum('amount');

            if ((int) $invoice->paid_amount !== (int) $actualPaid) {
                $discrepancies++;
                $this->warn("Invoice {$invoice->number}: stored={$invoice->paid_amount}, actual={$actualPaid}");

                if ($fix) {
                    $invoice->update([
                        'paid_amount' => $actualPaid,
                        'due_amount' => max(0, $invoice->total_amount - $actualPaid),
                    ]);

                    if ($actualPaid >= $invoice->total_amount && $invoice->status !== 'paid') {
                        $invoice->update(['status' => 'paid']);
                    } elseif ($actualPaid > 0 && $actualPaid < $invoice->total_amount && $invoice->status === 'paid') {
                        $invoice->update(['status' => 'partially_paid']);
                    }

                    $this->info("  → Fixed");
                }
            }
        }

        if ($discrepancies === 0) {
            $this->info("All {$invoices->count()} invoices reconcile correctly.");
        } else {
            $level = $fix ? 'info' : 'warn';
            $this->$level("{$discrepancies} discrepancies found" . ($fix ? ' and fixed.' : '. Run with --fix to correct.'));

            if (!$fix) {
                Log::warning("Financial reconciliation: {$discrepancies} discrepancies found");
            }
        }

        return self::SUCCESS;
    }
}
