<?php

namespace App\Listeners;

use App\Repositories\DealBuilderRepository;
use Illuminate\Support\Facades\Session;
use Mtc\Checkout\Events\PaidInvoice;
use Mtc\Checkout\InvoiceStatus;
use Mtc\MercuryDataModels\DealBuilder\Deal;
use Mtc\MercuryDataModels\DealBuilder\Status;

class ConfirmDealOnInvoicePayment
{
    public function __construct(private readonly DealBuilderRepository $repository)
    {
    }

    public function handle(PaidInvoice $event): void
    {
        if ($event->invoice->isPaid() && $event->invoice->getPayable() instanceof Deal) {
            /** @var Deal $deal */
            $deal = $event->invoice->getPayable();
            $paidInvoiceId = $event->invoice->getId();

            $initialStatus = Status::query()->where('is_initial', 1)->first();

            $deal->update([
                'status_id' => $initialStatus?->id,
            ]);

            // Track status change in history
            if ($deal->wasChanged('status_id') && $initialStatus) {
                $deal->history()->create([
                    'status_id' => $initialStatus->id,
                    'customer_id' => $deal->customer_id,
                ]);
            }

            // Remove all incomplete invoices for this deal (except the one just paid)
            $deal->invoices()
                ->where('id', '!=', $paidInvoiceId)
                ->where('status', '!=', InvoiceStatus::PAID)
                ->delete();

            Session::forget(DealBuilderRepository::DEAL_SESSION_KEY);
        }
    }
}
