<?php

declare(strict_types=1);

namespace App\Filament\Resources\Invoices\Pages;

use App\Filament\Resources\Invoices\InvoiceResource;
use App\Services\InvoiceService;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Auth;

class CreateInvoice extends CreateRecord
{
    protected static string $resource = InvoiceResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $data['created_by'] = Auth::id();
        $data['number'] = $data['number'] ?? app(InvoiceService::class)->generateNumber();
        $data['issued_at'] = $data['issued_at'] ?? now()->toDateString();

        return $data;
    }

    protected function afterCreate(): void
    {
        $total = (int) $this->record->items()->sum('total');
        $transport = (int) data_get($this->record->meta, 'transport.amount', 0);
        $this->record->update(['total' => $total + $transport]);
    }
}
