<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class SimpleRoleSeeder extends Seeder
{
    public function run(): void
    {
        // Check if roles table exists
        if (!DB::getSchemaBuilder()->hasTable('roles')) {
            $this->command->error('Roles table does not exist! Creating it...');
            
            // Create the table if it doesn't exist
            DB::statement('CREATE TABLE IF NOT EXISTS roles (
                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(255) NOT NULL,
                guard_name VARCHAR(255) NOT NULL,
                created_at TIMESTAMP NULL,
                updated_at TIMESTAMP NULL,
                UNIQUE KEY roles_name_guard_name_unique (name, guard_name)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
        }

        $roles = [
            ['name' => 'admin', 'guard_name' => 'web'],
            ['name' => 'employee', 'guard_name' => 'web'],
            ['name' => 'supervisor', 'guard_name' => 'web'],
        ];

        foreach ($roles as $role) {
            if (!DB::table('roles')->where('name', $role['name'])->exists()) {
                DB::table('roles')->insert([
                    'name' => $role['name'],
                    'guard_name' => $role['guard_name'],
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
                $this->command->info("Role '{$role['name']}' created.");
            } else {
                $this->command->info("Role '{$role['name']}' already exists.");
            }
        }

        $this->command->info('Roles seeding completed successfully!');
    }
}