<?php

namespace Database\Seeders;

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

class PermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        // All recommended permissions
        $permissions = [
            'dashboard.view',

            'users.view',
            'users.create',
            'users.update',
            'users.delete',

            'roles.view',
            'roles.create',
            'roles.update',
            'roles.delete',

            'products.view',
            'products.create',
            'products.update',
            'products.delete',
            'products.export',
            'products.update-availability',

            'categories.view',
            'categories.create',
            'categories.update',
            'categories.delete',

            'brands.view',
            'brands.create',
            'brands.update',
            'brands.delete',

            'units.view',
            'units.create',
            'units.update',
            'units.delete',

            'attributes.view',
            'attributes.create',
            'attributes.update',
            'attributes.delete',

            'customers.view',
            'customers.create',
            'customers.update',
            'customers.delete',
            'customers.export',

            'shipping-methods.view',
            'shipping-methods.create',
            'shipping-methods.update',
            'shipping-methods.delete',

            'orders.view',
            'orders.create',
            'orders.update',
            'orders.cancel',
            'orders.refund',

            'payments.view',
            'payments.verify',
            'payments.refund',

            'reviews.view',
            'reviews.approve',
            'reviews.reject',
            'reviews.delete',

            'cms.pages.view',
            'cms.pages.create',
            'cms.pages.update',
            'cms.pages.delete',
            'cms.pages.publish',

            'reports.sales',
            'reports.orders',
            'reports.payments',
            'reports.products',
            'reports.customers',

            'settings.view',
            'settings.update',

            'activity-logs.view',
        ];

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

        // Create Roles
        $superAdminRole = Role::firstOrCreate(['name' => 'Super Admin', 'guard_name' => 'web']);
        $adminRole = Role::firstOrCreate(['name' => 'Admin', 'guard_name' => 'web']);
        $staffRole = Role::firstOrCreate(['name' => 'Staff', 'guard_name' => 'web']);

        // Super Admin gets all permissions implicitly via Gate::before in AppServiceProvider.
        // But we can also sync them here to be explicit
        $superAdminRole->syncPermissions(Permission::all());

        // Admin gets everything except deleting users and roles
        $adminPermissions = Permission::whereNotIn('name', [
            'users.delete',
            'roles.delete',
        ])->get();
        $adminRole->syncPermissions($adminPermissions);

        // Staff gets view permissions + catalog edit/create
        $staffPermissions = Permission::whereIn('name', [
            'dashboard.view',
            'products.view',
            'products.create',
            'products.update',
            'products.update-availability',
            'categories.view',
            'categories.create',
            'categories.update',
            'brands.view',
            'brands.create',
            'brands.update',
            'units.view',
            'units.create',
            'units.update',
            'attributes.view',
            'attributes.create',
            'attributes.update',
            'customers.view',
            'shipping-methods.view',
            'orders.view',
            'orders.update',
            'payments.view',
            'reviews.view',
            'reviews.approve',
            'reviews.reject',
            'cms.pages.view',
            'cms.pages.create',
            'cms.pages.update',
            'cms.pages.publish',
            'reports.sales',
            'reports.orders',
            'reports.payments',
            'reports.products',
            'reports.customers',
            'settings.view',
        ])->get();
        $staffRole->syncPermissions($staffPermissions);

        // Assign Role to default admin user
        $defaultAdmin = User::where('email', 'admin@example.com')->first();
        if ($defaultAdmin) {
            $defaultAdmin->assignRole($superAdminRole);
        }

        // Also assign roles to any existing admins based on their user role field
        $admins = User::whereIn('role', ['admin', 'super_admin'])->get();
        foreach ($admins as $user) {
            if ($user->role === 'super_admin') {
                $user->assignRole($superAdminRole);
            } else {
                $user->assignRole($adminRole);
            }
        }
    }
}
