<?php

namespace App\Filament\Resources\Consultants\Pages;

use App\Filament\Resources\Consultants\ConsultantResource;
use App\Mail\ConsultantInviteMail;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class CreateConsultant extends CreateRecord
{
    protected static string $resource = ConsultantResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        return [
            ...$data,
            'invite_token' => Str::random(48),
            'invited_by' => auth()->id(),
            'invited_at' => now(),
        ];
    }

    protected function afterCreate(): void
    {
        try {
            Mail::to($this->record->email)->send(new ConsultantInviteMail($this->record));

            Notification::make()
                ->title('Invite sent to '.$this->record->email)
                ->success()
                ->send();
        } catch (\Throwable) {
            Notification::make()
                ->title('Invite created, but the email could not be sent')
                ->body('Copy the invite link from the list and share it directly. Check Settings > Configurations for email setup.')
                ->warning()
                ->send();
        }
    }
}
