<?php

namespace App\Filament\Resources\MainCategoryResource\Pages;

use App\Filament\Resources\MainCategoryResource;
use App\Models\Catalog\MainCategory;
use App\Services\AuditLog;
use Filament\Resources\Pages\EditRecord;

class EditMainCategory extends EditRecord
{
    protected static string $resource = MainCategoryResource::class;

    /**
     * @var array<string, mixed>
     */
    protected array $originalValues = [];

    protected function mutateFormDataBeforeSave(array $data): array
    {
        $this->originalValues = $this->record->only(['name', 'description', 'is_active']);

        return $data;
    }

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

        $changes = [];
        foreach ($this->originalValues as $field => $old) {
            if ($old !== $category->{$field}) {
                $changes[$field] = ['from' => $old, 'to' => $category->{$field}];
            }
        }

        AuditLog::record('main_category.updated', $category, [
            'name' => $category->name,
            'changed' => array_keys($changes),
            'changes' => $changes,
            'description' => 'Updated main category "'.$category->name.'"'
                .($changes !== [] ? ' — changed: '.implode(', ', array_keys($changes)) : '').'.',
        ]);
    }

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