<?php

namespace App\Filament\Resources\TillResource\Pages;

use App\Filament\Resources\TillResource;
use App\Models\Sales\Till;
use App\Services\AuditLog;
use App\Services\DocumentNumberService;
use Filament\Resources\Pages\CreateRecord;

class CreateTill extends CreateRecord
{
    protected static string $resource = TillResource::class;

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeCreate(array $data): array
    {
        if (filled($data['branch_id'] ?? null)) {
            TillResource::assertBranchAccessible((int) $data['branch_id']);
        }

        $data['identifier'] = app(DocumentNumberService::class)->next('till');

        return $data;
    }

    /**
     * Mirrors TillController::store()'s audit entry exactly, including the
     * human-readable `description` string.
     */
    protected function afterCreate(): void
    {
        /** @var Till $till */
        $till = $this->record;

        AuditLog::record('till.created', $till, [
            'name' => $till->name,
            'description' => 'Created till "'.$till->name.'" ('.$till->identifier.').',
        ]);
    }
}
