<?php

declare(strict_types=1);

namespace App\Filament\Resources\AlertDestinationResource\Pages;

use App\Filament\Resources\AlertDestinationResource;
use App\Models\AlertDestination;
use App\Support\Audit\AuditActionId;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;

class CreateAlertDestination extends CreateRecord
{
    protected static string $resource = AlertDestinationResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $workspaceId = app(\App\Support\Workspaces\WorkspaceContext::class)->currentWorkspaceId(request());
        $data['workspace_id'] = (int) $workspaceId;
        $data = AlertDestinationResource::normalizePayload($data);
        AlertDestinationResource::assertValidConfigPayload($data);

        return $data;
    }

    protected function afterCreate(): void
    {
        $record = $this->record;

        if (! $record instanceof AlertDestination) {
            return;
        }

        AlertDestinationResource::audit($record, AuditActionId::AlertDestinationCreated, [
            'alert_destination_id' => (int) $record->getKey(),
            'name' => (string) $record->name,
            'type' => (string) $record->type,
            'is_enabled' => (bool) $record->is_enabled,
        ]);

        Notification::make()
            ->title('Destination created')
            ->success()
            ->send();
    }
}
