<?php

namespace Database\Seeders;

use App\Domain\Identity\Models\Role;
use App\Domain\Shared\Models\Academy;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $adminEmail = env('ADMIN_EMAIL', 'admin@elcaptain.com');
        $adminPassword = env('ADMIN_PASSWORD', 'Alarcade123#');
        $adminName = env('ADMIN_NAME', env('ACADEMY_NAME_AR', 'أكاديمية الكابتن'));

        // Single academy per instance — use whatever exists, only create if empty
        $academy = Academy::first();
        if (!$academy) {
            $academy = Academy::create([
                'name' => env('ACADEMY_NAME_EN', 'El Captain Academy'),
                'name_ar' => env('ACADEMY_NAME_AR', 'أكاديمية الكابتن'),
                'slug' => Str::slug(env('ACADEMY_NAME_EN', 'El Captain Academy')),
                'email' => $adminEmail,
                'currency' => 'EGP',
                'timezone' => 'Africa/Cairo',
                'locale' => 'ar',
                'status' => 'active',
            ]);
        }

        // Admin user — always on THE academy
        $admin = User::firstOrCreate(
            ['email' => $adminEmail],
            [
                'academy_id' => $academy->id,
                'name' => $adminName,
                'name_ar' => $adminName,
                'email' => $adminEmail,
                'password' => Hash::make($adminPassword),
                'status' => 'active',
            ]
        );

        // Ensure admin is on the correct academy
        if ($admin->academy_id !== $academy->id) {
            $admin->update(['academy_id' => $academy->id]);
        }

        $this->call(FinancialAccountsSeeder::class);
        // After the chart: a routing rule points at an account by id, so the
        // accounts have to exist before the rules can be written.
        $this->call(RevenueRoutingSeeder::class);
        $this->call(RolesAndPermissionsSeeder::class);
        $this->call(PermissionSeeder::class);
        $this->call(PaymentNotificationTemplateSeeder::class);
        $this->call(EnrollmentSettingsSeeder::class);

        // Assign academy_owner role + super_admin
        $ownerRole = Role::where('academy_id', $academy->id)
            ->where('slug', 'academy_owner')
            ->first();

        $admin->update([
            'role_id' => $ownerRole?->id ?? $admin->role_id,
            'is_super_admin' => true,
        ]);

        if ($ownerRole && !$admin->roles()->where('role_id', $ownerRole->id)->exists()) {
            $admin->roles()->attach($ownerRole->id);
        }
    }
}
