<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * Add `settlements.manage` and grant it to the roles that answer for the money.
 *
 * Settling an account writes payments, waives balances and bills months that
 * were never billed. That is the academy's own decision to make, not the front
 * desk's — hence owner and admin, not receptionist.
 *
 * PermissionSeeder lists it too, but db:seed only runs on a first deploy
 * (docker/entrypoint.sh), while migrations always run. Idempotent: every insert
 * checks for the row first, so repeated container starts are harmless.
 */
return new class extends Migration
{
    private const PERMISSION = 'settlements.manage';

    private const ROLES = ['super_admin', 'academy_owner', 'academy_admin'];

    public function up(): void
    {
        if (! Schema::hasTable('permissions') || ! Schema::hasTable('permission_role')) {
            return;
        }

        $permissionId = DB::table('permissions')
            ->where('name', self::PERMISSION)
            ->value('id');

        if (! $permissionId) {
            $permissionId = DB::table('permissions')->insertGetId([
                'name' => self::PERMISSION,
                'module' => 'settlements',
                'action' => 'manage',
                'description' => 'Settle a participant account: back-dated payments, waivers, retroactive sales',
                'description_ar' => 'تسوية حساب مشترك: دفعات سابقة، إسقاط مستحقات، مبيعات بأثر رجعي',
                'created_at' => now(),
            ]);
        }

        if (! Schema::hasTable('roles')) {
            return;
        }

        // Roles are per-academy, so this covers every tenant in the database.
        $roleIds = DB::table('roles')
            ->whereIn('slug', self::ROLES)
            ->pluck('id');

        foreach ($roleIds as $roleId) {
            $exists = DB::table('permission_role')
                ->where('role_id', $roleId)
                ->where('permission_id', $permissionId)
                ->exists();

            if (! $exists) {
                DB::table('permission_role')->insert([
                    'role_id' => $roleId,
                    'permission_id' => $permissionId,
                    'scope' => 'all',
                    'created_at' => now(),
                ]);
            }
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('permissions')) {
            return;
        }

        $permissionId = DB::table('permissions')
            ->where('name', self::PERMISSION)
            ->value('id');

        if (! $permissionId) {
            return;
        }

        if (Schema::hasTable('permission_role')) {
            DB::table('permission_role')->where('permission_id', $permissionId)->delete();
        }

        DB::table('permissions')->where('id', $permissionId)->delete();
    }
};
