<?php

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

/**
 * `plans.manage` — create plans, publish versions, set what is on sale and when,
 * and pull a plan from the shop.
 *
 * Owner and Admin only. This is what the business charges for: publishing a
 * version fixes terms that customers are then contracted to, and the kill
 * switch decides whether anything can be bought at all.
 */
return new class extends Migration
{
    public function up(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        Permission::findOrCreate('plans.manage', 'web');
        foreach (['Owner', 'Admin'] as $role) {
            Role::findOrCreate($role, 'web')->givePermissionTo('plans.manage');
        }

        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }

    public function down(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();
        Permission::query()->where('name', 'plans.manage')->delete();
        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }
};
