<?php

namespace App\Filament\Central\Resources\CompanyResource\Pages;

use App\Filament\Central\Resources\CompanyResource;
use App\Services\CompanyProvisioner;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;

class CreateCompany extends CreateRecord
{
    protected static string $resource = CompanyResource::class;

    /** Override the standard create flow: delegate to CompanyProvisioner. */
    protected function handleRecordCreation(array $data): \Illuminate\Database\Eloquent\Model
    {
        $result = app(CompanyProvisioner::class)->provision($data);

        $msg = "Admin: {$result['admin_email']}\nParolă: {$result['admin_password']}";
        if ($result['deploy_triggered']) {
            $msg .= "\n✅ Subdomain adăugat în Coolify, redeploy declanșat (~90s).";
        } else {
            $detail = $result['coolify_message'] ?? 'unknown';
            $msg .= "\n⚠️ Provisioning automat eșuat ({$detail}). Adaugă manual https://{$result['company']->slug}.service.mir.md:8000 la FQDN-ul aplicației.";
        }

        Notification::make()
            ->title("Companie creată: {$result['company']->name}")
            ->body($msg)
            ->persistent()
            ->success()
            ->send();

        return $result['company'];
    }
}
