<?php

namespace App\Filament\Resources\SubCategoryResource\Pages;

use App\Filament\Resources\SubCategoryResource;
use App\Models\Catalog\MainCategory;
use App\Models\Catalog\SubCategory;
use App\Services\AuditLog;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Validation\ValidationException;

class CreateSubCategory extends CreateRecord
{
    protected static string $resource = SubCategoryResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // Defense-in-depth: the form's Select already restricts choices to
        // active parents, but a crafted request could still submit an
        // inactive one — matches the source controller's explicit guard.
        if (! MainCategory::where('id', $data['main_category_id'])->where('is_active', true)->exists()) {
            throw ValidationException::withMessages([
                'main_category_id' => 'The selected main category is inactive.',
            ]);
        }

        $data['sort_code'] = SubCategoryResource::generateSortCode($data['name']);

        return $data;
    }

    protected function afterCreate(): void
    {
        /** @var SubCategory $category */
        $category = $this->record;

        AuditLog::record('sub_category.created', $category, [
            'name' => $category->name,
            'description' => 'Created sub category "'.$category->name.'" under "'.($category->mainCategory?->name ?? '?').'".',
        ]);
    }

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