<?php

namespace Database\Seeders;

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Stancl\Tenancy\Jobs\CreateDatabase; // <--- Import the Job

class TenantSeeder extends Seeder
{
    public function run(): void
    {
        // 1. Get or Create the Tenant
        // firstOrCreate is safe: if 'dennis' exists, it returns it; if not, it creates it.
        $tenant = Tenant::firstOrCreate(['id' => 'dennis'], [
            'firm_name' => 'Dennis Law Chambers',
            'email' => 'admin@dennislaw.test',
            'plan' => 'premium',
            'subscription_status' => 'active',
            'total_paid' => 15000.00,
        ]);

        // 2. Ensure Domain Exists
        $tenant->domains()->firstOrCreate(['domain' => 'dennis.legalpro.test']);

        // 3. FORCE Database Creation (The Correct Way)
        // We dispatch the job synchronously. This triggers the exact same logic
        // as the event listener, but forces it to happen NOW.
        try {
            dispatch_sync(new CreateDatabase($tenant));
        } catch (\Throwable $e) {
            // If the database already exists, this might throw an error.
            // We catch it and continue, effectively saying "Ensure it exists."
        }

        // 4. Run Logic INSIDE the Tenant Context
        $tenant->run(function () {
            // Optional: Run migrations explicitly to ensure tables exist
            // This is helpful if the DB existed but was empty
            \Illuminate\Support\Facades\Artisan::call('tenants:migrate');

            // Create the Admin User
            User::firstOrCreate(['email' => 'admin@dennislaw.test'], [
                'name' => 'Dennis (Lawyer)',
                'password' => Hash::make('password'),
                'role' => 'admin',
            ]);
        });
    }
}
