<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

return new class extends Migration
{
    /**
     * All granular permissions grouped by category.
     *
     * @var array<string, list<string>>
     */
    private const PERMISSION_GROUPS = [
        'customers' => [
            'customers.view',
            'customers.edit',
            'customers.create',
            'customers.delete',
            'customers.suspend',
            'customers.impersonate',
        ],
        'services' => [
            'services.view',
            'services.suspend',
            'services.terminate',
            'services.provision',
            'services.extend',
        ],
        'invoices' => [
            'invoices.view',
            'invoices.create',
            'invoices.edit',
            'invoices.void',
            'invoices.refund',
        ],
        'tickets' => [
            'tickets.view',
            'tickets.reply',
            'tickets.assign',
            'tickets.close',
            'tickets.delete',
        ],
        'reports' => [
            'reports.view',
            'reports.export',
        ],
        'settings' => [
            'settings.view',
            'settings.edit',
        ],
        'audit_logs' => [
            'audit_logs.view',
            'audit_logs.export',
        ],
        'plans' => [
            'plans.view',
            'plans.create',
            'plans.edit',
            'plans.delete',
        ],
        'coupons' => [
            'coupons.view',
            'coupons.create',
            'coupons.edit',
            'coupons.delete',
        ],
        'credit_notes' => [
            'credit_notes.view',
            'credit_notes.create',
            'credit_notes.void',
        ],
        'debit_notes' => [
            'debit_notes.view',
            'debit_notes.create',
            'debit_notes.void',
        ],
        'affiliates' => [
            'affiliates.view',
            'affiliates.approve',
            'affiliates.payout',
        ],
        'staff' => [
            'staff.view',
            'staff.manage',
        ],
    ];

    public function up(): void
    {
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Create all granular permissions (idempotent)
        foreach (self::PERMISSION_GROUPS as $permissions) {
            foreach ($permissions as $permission) {
                Permission::firstOrCreate(['name' => $permission, 'guard_name' => 'web']);
            }
        }

        $allPermissions = Permission::where('guard_name', 'web')->pluck('name')->toArray();
        $allGranular = collect(self::PERMISSION_GROUPS)->flatten()->toArray();

        // super_admin — ALL permissions
        $superAdmin = Role::firstOrCreate(['name' => 'super_admin', 'guard_name' => 'web']);
        $superAdmin->syncPermissions($allPermissions);

        // admin — ALL permissions (backward compat, interchangeable with super_admin)
        $admin = Role::firstOrCreate(['name' => 'admin', 'guard_name' => 'web']);
        $admin->syncPermissions($allPermissions);

        // billing_admin
        $billingAdmin = Role::firstOrCreate(['name' => 'billing_admin', 'guard_name' => 'web']);
        $billingAdmin->syncPermissions([
            'customers.view', 'customers.edit',
            'invoices.view', 'invoices.create', 'invoices.edit', 'invoices.void', 'invoices.refund',
            'services.view', 'services.suspend',
            'reports.view', 'reports.export',
            'credit_notes.view', 'credit_notes.create', 'credit_notes.void',
            'debit_notes.view', 'debit_notes.create', 'debit_notes.void',
            'plans.view',
        ]);

        // support_agent
        $supportAgent = Role::firstOrCreate(['name' => 'support_agent', 'guard_name' => 'web']);
        $supportAgent->syncPermissions([
            'customers.view',
            'tickets.view', 'tickets.reply',
            'services.view',
        ]);

        // support_lead
        $supportLead = Role::firstOrCreate(['name' => 'support_lead', 'guard_name' => 'web']);
        $supportLead->syncPermissions([
            'customers.view', 'customers.edit',
            'tickets.view', 'tickets.reply', 'tickets.assign', 'tickets.close', 'tickets.delete',
            'services.view',
        ]);

        // readonly_admin — all *.view permissions only
        $readonlyAdmin = Role::firstOrCreate(['name' => 'readonly_admin', 'guard_name' => 'web']);
        $viewPermissions = collect($allGranular)->filter(fn (string $p): bool => str_ends_with($p, '.view'))->toArray();
        $readonlyAdmin->syncPermissions($viewPermissions);

        // Ensure customer role exists
        Role::firstOrCreate(['name' => 'customer', 'guard_name' => 'web']);

        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
    }

    public function down(): void
    {
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Remove new roles (keep admin and customer)
        Role::whereIn('name', ['super_admin', 'billing_admin', 'support_agent', 'support_lead', 'readonly_admin'])->delete();

        // Remove granular permissions
        $allGranular = collect(self::PERMISSION_GROUPS)->flatten()->toArray();
        Permission::whereIn('name', $allGranular)->delete();

        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
    }
};
