<?php

namespace App\Filament\Blog\Resources\CategoryResource\Pages;

use App\Filament\Blog\Resources\CategoryResource;
use App\Filament\Resources\Pages\AuditedEditRecord;
use App\Services\Audit\SuperAdminAuditLogger;
use Filament\Actions;

class EditCategory extends AuditedEditRecord
{
    protected static string $resource = CategoryResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\DeleteAction::make()
                ->after(fn ($record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                    'deleted',
                    $record,
                    source: static::class
                )),
        ];
    }

    protected function getFormValidationRules(): array
    {
        return [
            'name_de' => 'required|string|max:255',
            'description_de' => 'nullable|string',
            'name_en' => 'nullable|string|max:255',
            'description_en' => 'nullable|string',
            'slug' => 'required|string|max:255|unique:blog_categories,slug,'.$this->record->id,
            'is_visible' => 'boolean',
        ];
    }

    public function mount($record): void
    {
        parent::mount($record);
        $data = $this->record->toArray();
        $data = \App\Filament\Blog\Resources\CategoryResource::mutateFormDataBeforeFill($data);
        $this->form->fill($data);
    }

    public function save(bool $shouldRedirect = true, bool $shouldSendSavedNotification = true): void
    {
        $state = $this->form->getState();

        $data = $state['data'] ?? $state;

        $data = \App\Filament\Blog\Resources\CategoryResource::mutateFormDataBeforeSave($data);

        $this->record->update($data);

        parent::afterSave();
    }
}
