<?php

namespace App\Console\Commands\Migrations;

use Spatie\Permission\Models\Role;

class RolesMigration extends BaseMigration
{
    /**
     * Roles to be created
     */
    protected array $roles = [
        'مدير جمعية',
        'مدير التخطيط',
        'مدير مشروع',
        'مدير إدارة المشاريع',
        'مدير التصنيف',
        'المحاسب',
        'مراجع الحسابات',
        'مدير الخدمات المشتركة',
        'الرئيس التنفيذي',
    ];

    /**
     * Execute the roles migration
     */
    public function migrate(bool $dryRun, int $batchSize, int $startFrom): void
    {
        $this->info('🔐 Starting roles migration...');

        $this->stats['total'] = count($this->roles);

        $this->info('📊 Found '.count($this->roles).' roles to create');

        // Process each role
        $bar = $this->command->getOutput()->createProgressBar(count($this->roles));

        foreach ($this->roles as $roleName) {
            try {
                if (! $dryRun) {
                    // Check if role already exists
                    if (Role::where('name', $roleName)->exists()) {
                        $this->info("📝 Role '{$roleName}' already exists, skipping");
                        $this->stats['skipped']++;
                    } else {
                        Role::create(['name' => $roleName]);
                        $this->info("✅ Created role: {$roleName}");
                        $this->stats['migrated']++;
                    }
                } else {
                    // In dry-run mode, just check if it would be created
                    if (Role::where('name', $roleName)->exists()) {
                        $this->stats['skipped']++;
                    } else {
                        $this->stats['migrated']++;
                    }
                }
            } catch (\Exception $e) {
                $this->stats['errors']++;
                $this->error("❌ Error creating role '{$roleName}': ".$e->getMessage());
            }

            $bar->advance();
        }

        $bar->finish();
        $this->command->newLine();
        $this->info('✅ Roles migration completed');
    }

    /**
     * Get the model name for display purposes
     */
    protected function getModelName(): string
    {
        return 'Role';
    }

    /**
     * Get the model class name
     */
    protected function getModelClass(): string
    {
        return Role::class;
    }

    /**
     * Map data - not used for roles as they're predefined
     */
    protected function mapData(object $oldRecord): array
    {
        return [];
    }

    /**
     * Validate data - not used for roles as they're predefined
     */
    protected function validateData(array $data): bool
    {
        return true;
    }

    /**
     * Get all available roles
     */
    public function getRoles(): array
    {
        return $this->roles;
    }
}
