<?php

namespace Database\Seeders;

use App\Enums\UserRole;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        $permissions = [
            // SuperAdmin
            'saas.manage', 'companies.manage', 'plans.manage', 'subscriptions.manage',
            'modules.manage', 'global_reports.view', 'activity_logs.view',

            // Empresa
            'company.manage', 'company.settings',
            'employees.view', 'employees.manage',
            'services.view', 'services.manage',
            'schedules.manage',
            'customers.view', 'customers.manage',
            'bookings.view', 'bookings.create', 'bookings.update', 'bookings.cancel',
            'reports.view',
            'promotions.manage', 'coupons.manage',
            'payments.view', 'payments.manage',
            'gallery.manage',

            // Clínico (acceso restringido)
            'clinical_history.view', 'clinical_history.edit',
            'consent_forms.manage', 'client_files.manage',

            // Empleado
            'agenda.view', 'bookings.update_own',
        ];

        foreach ($permissions as $perm) {
            Permission::firstOrCreate(['name' => $perm, 'guard_name' => 'web']);
        }

        // Súper Admin
        $superAdmin = Role::firstOrCreate(['name' => UserRole::SuperAdmin->value, 'guard_name' => 'web']);
        $superAdmin->syncPermissions(Permission::all());

        // Admin de empresa
        $companyAdmin = Role::firstOrCreate(['name' => UserRole::CompanyAdmin->value, 'guard_name' => 'web']);
        $companyAdmin->syncPermissions([
            'company.manage', 'company.settings',
            'employees.view', 'employees.manage',
            'services.view', 'services.manage',
            'schedules.manage',
            'customers.view', 'customers.manage',
            'bookings.view', 'bookings.create', 'bookings.update', 'bookings.cancel',
            'reports.view',
            'promotions.manage', 'coupons.manage',
            'payments.view', 'payments.manage',
            'gallery.manage',
            'clinical_history.view', 'clinical_history.edit',
            'consent_forms.manage', 'client_files.manage',
        ]);

        // Empleado
        $employee = Role::firstOrCreate(['name' => UserRole::Employee->value, 'guard_name' => 'web']);
        $employee->syncPermissions([
            'agenda.view', 'bookings.view', 'bookings.update_own',
            'customers.view',
        ]);

        // Cliente final (no usado mucho, solo si el cliente se registra)
        Role::firstOrCreate(['name' => UserRole::Customer->value, 'guard_name' => 'web']);
    }
}
