<?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;

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

        $slug = \Illuminate\Support\Str::slug($academyNameEn);

        $academy = Academy::firstOrCreate(
            ['slug' => $slug],
            [
                'name' => $academyNameEn,
                'name_ar' => $academyNameAr,
                'slug' => $slug,
                'email' => $adminEmail,
                'currency' => 'EGP',
                'timezone' => 'Africa/Cairo',
                'locale' => 'ar',
                'status' => 'active',
            ]
        );

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

        $this->call(FinancialAccountsSeeder::class);
        $this->call(RolesAndPermissionsSeeder::class); // Creates roles (needed before PermissionSeeder)
        $this->call(PermissionSeeder::class); // Authoritative permission+scope assignments
        $this->call(PaymentNotificationTemplateSeeder::class);

        // Assign academy_owner role to the admin user (check user's own academy first)
        $ownerRole = Role::where('academy_id', $admin->academy_id)
            ->where('slug', 'academy_owner')
            ->first()
            ?? Role::where('academy_id', $academy->id)
                ->where('slug', 'academy_owner')
                ->first();

        // Ensure admin has branch assigned
        $branch = \App\Domain\Identity\Models\Branch::where('academy_id', $admin->academy_id)->first();
        $branchId = $branch?->id ?? $admin->branch_id;

        if ($ownerRole) {
            $admin->update(['role_id' => $ownerRole->id, 'is_super_admin' => true, 'branch_id' => $branchId]);
            if (!$admin->roles()->where('role_id', $ownerRole->id)->exists()) {
                $admin->roles()->attach($ownerRole->id);
            }
        } else {
            $admin->update(['is_super_admin' => true, 'branch_id' => $branchId]);
        }
    }
}
