<?php

namespace Database\Seeders;

use App\Models\Association;
use App\Models\AssociationRole;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class AssociationRolesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->command->info('Creating default roles for all associations...');

        $associations = Association::all();

        foreach ($associations as $association) {
            $this->command->info("Processing: {$association->name}");

            // Get default roles
            $defaultRoles = AssociationRole::getDefaultRoles();

            foreach ($defaultRoles as $roleData) {
                // Check if role already exists
                $existingRole = AssociationRole::where('association_id', $association->id)
                    ->where('slug', $roleData['slug'])
                    ->first();

                if (!$existingRole) {
                    $role = AssociationRole::create([
                        'association_id' => $association->id,
                        'name' => $roleData['name'],
                        'slug' => $roleData['slug'],
                        'description' => $roleData['description'],
                        'can_access_admin_panel' => $roleData['can_access_admin_panel'],
                        'is_system_role' => $roleData['is_system_role'],
                        'sort_order' => $roleData['sort_order'],
                        'permissions' => $roleData['permissions'],
                    ]);

                    $this->command->info("  ✓ Created role: {$role->name}");
                } else {
                    $this->command->info("  - Role already exists: {$roleData['name']}");
                }
            }
        }

        $this->command->info('✅ Default roles created successfully!');

        // Migrate existing string roles to role_id
        $this->migrateExistingRoles();
    }

    /**
     * Migrate existing string-based roles to role_id references
     */
    protected function migrateExistingRoles(): void
    {
        $this->command->info('');
        $this->command->info('Migrating existing member roles...');

        $pivots = DB::table('association_user')
            ->whereNull('role_id')
            ->whereNotNull('role')
            ->get();

        foreach ($pivots as $pivot) {
            // Map old role string to role slug
            $roleSlugMap = [
                'Member' => 'member',
                'Executive' => 'executive',
                'Admin' => 'admin',
                'President' => 'president',
                'Vice President' => 'vice-president',
                'Secretary' => 'secretary',
                'Treasurer' => 'treasurer',
            ];

            $roleSlug = $roleSlugMap[$pivot->role] ?? 'member';

            // Find the role
            $role = AssociationRole::where('association_id', $pivot->association_id)
                ->where('slug', $roleSlug)
                ->first();

            if ($role) {
                DB::table('association_user')
                    ->where('user_id', $pivot->user_id)
                    ->where('association_id', $pivot->association_id)
                    ->update(['role_id' => $role->id]);

                $this->command->info("  ✓ Migrated user {$pivot->user_id} from '{$pivot->role}' to role ID {$role->id}");
            }
        }

        $this->command->info('✅ Migration complete!');
    }
}
