<?php

namespace App\Filament\Resources\CreditNoteResource\Pages;

use App\Filament\Resources\CreditNoteResource;
use App\Models\Lookups\Status;
use App\Models\Returns\CreditNote;
use App\Services\CreditNoteService;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\DB;

/**
 * Ported from CreditNoteController::store(). The service owns numbering (a
 * race-safe document sequence), the draft→issued transition, and crediting the
 * customer's pool — so nothing here writes to CreditNote directly.
 */
class CreateCreditNote extends CreateRecord
{
    protected static string $resource = CreditNoteResource::class;

    protected function handleRecordCreation(array $data): CreditNote
    {
        return DB::transaction(function () use ($data): CreditNote {
            $creditNotes = app(CreditNoteService::class);

            $cn = $creditNotes->createManualDraft(
                customerId: (int) $data['customer_id'],
                amount: (float) $data['amount'],
                note: $data['note'] ?? null,
            );

            if ($data['status_code'] === Status::ISSUED) {
                $creditNotes->issue($cn->refresh());
            }

            return $cn->refresh();
        });
    }

    protected function getRedirectUrl(): string
    {
        return CreditNoteResource::getUrl('index');
    }
}
