<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * 
     * 新增配方管理權限
     */
    public function up(): void
    {
        $guard = 'web';
        
        // 建立配方管理權限
        $permissions = [
            'recipes.view' => '檢視配方',
            'recipes.create' => '建立配方',
            'recipes.edit' => '編輯配方',
            'recipes.delete' => '刪除配方',
        ];

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

        // 授予 super-admin 所有新權限
        $superAdmin = Role::where('name', 'super-admin')->first();
        if ($superAdmin) {
            $superAdmin->givePermissionTo(array_keys($permissions));
        }

        // 授予 admin 所有新權限
        $admin = Role::where('name', 'admin')->first();
        if ($admin) {
            $admin->givePermissionTo(array_keys($permissions));
        }

        // 授予 warehouse-manager 檢視權限 (配方通常與庫存相關)
        $whManager = Role::where('name', 'warehouse-manager')->first();
        if ($whManager) {
            $whManager->givePermissionTo(['recipes.view']);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $permissions = [
            'recipes.view',
            'recipes.create',
            'recipes.edit',
            'recipes.delete',
        ];

        foreach ($permissions as $name) {
            Permission::where('name', $name)->delete();
        }
    }
};
