<?php

declare(strict_types=1);

namespace App\Filament\Resources\AlertRuleResource\Pages;

use App\Filament\Resources\AlertRuleResource;
use App\Models\AlertRule;
use App\Support\Audit\AuditActionId;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Arr;

class CreateAlertRule extends CreateRecord
{
    protected static string $resource = AlertRuleResource::class;

    /**
     * @var array<int, int>
     */
    private array $destinationIds = [];

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

        $this->destinationIds = array_values(array_unique(array_filter(array_map(
            static fn (mixed $value): int => (int) $value,
            Arr::wrap($data['destination_ids'] ?? []),
        ))));

        unset($data['destination_ids']);

        return AlertRuleResource::normalizePayload($data);
    }

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

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

        AlertRuleResource::syncDestinations($record, $this->destinationIds);

        AlertRuleResource::audit($record, AuditActionId::AlertRuleCreated, [
            'alert_rule_id' => (int) $record->getKey(),
            'name' => (string) $record->name,
            'event_type' => (string) $record->event_type,
            'minimum_severity' => (string) $record->minimum_severity,
            'is_enabled' => (bool) $record->is_enabled,
            'destination_ids' => $this->destinationIds,
        ]);

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