<?php

namespace App\Filament\Resources\BroadcastCampaignResource\Pages;

use App\Filament\Resources\BroadcastCampaignResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditBroadcastCampaign extends EditRecord
{
    protected static string $resource = BroadcastCampaignResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\ViewAction::make(),
            Actions\DeleteAction::make()
                ->visible(fn () => $this->record->isEditable()),
        ];
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('view', ['record' => $this->record]);
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // If targeting filters changed, regenerate recipients
        if ($this->record->isDirty('target_filters') && $this->record->status === 'draft') {
            // Will be handled after save in afterSave method
        }
        
        return $data;
    }

    protected function afterSave(): void
    {
        // If this is a draft campaign and targeting changed, regenerate recipients
        if ($this->record->status === 'draft' && $this->record->wasChanged('target_filters')) {
            // Delete existing recipients
            $this->record->recipients()->delete();
            
            // Regenerate recipients
            app(\App\Services\Notification\NotificationService::class)->generateRecipients($this->record);
        }
    }
}