<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

/**
 * Backfill: assign the new VetClinic permissions added in recent migrations
 * to every business's Admin role + every role that already holds
 * vet_clinic.access_module. Without this step, even after the create
 * migrations register the permission, no one gets it — which is why the
 * "Unblock" button on the owner banner and the Owner Blocking menu entry
 * appeared invisible/non-functional for existing installs.
 *
 * Permissions covered (all new in the recent feature wave):
 *   - vet_clinic.manage_owner_blocking
 *   - vet_clinic.view_owner_blocking
 *   - vet_clinic.view_critical_report
 *   - vet_clinic.manage_exam_templates
 *   - vet_clinic.record_exam_findings
 *   - vet_clinic.view_exam_findings
 *
 * Safe to re-run: Spatie's givePermissionTo is idempotent (silently
 * skips already-granted assignments).
 */
class AssignNewVetClinicPermissionsToAdmin extends Migration
{
    public function up()
    {
        $newPerms = [
            'vet_clinic.manage_owner_blocking',
            'vet_clinic.view_owner_blocking',
            'vet_clinic.view_critical_report',
            'vet_clinic.manage_exam_templates',
            'vet_clinic.record_exam_findings',
            'vet_clinic.view_exam_findings',
        ];
        // Resolve the permission models (skip silently if a permission isn't
        // present yet — e.g. a partial-install state).
        $perms = Permission::whereIn('name', $newPerms)->get();
        if ($perms->isEmpty()) return;

        // Strategy: any role that already holds vet_clinic.access_module
        // is a "VetClinic user" — grant the new perms to that role.
        // PLUS any Admin#<business_id> role (UltimatePOS naming) gets them too.
        $accessRole = Permission::where('name', 'vet_clinic.access_module')->first();
        $rolesWithAccess = $accessRole
            ? DB::table('model_has_permissions')
                ->where('permission_id', $accessRole->id)
                ->where('model_type', \Spatie\Permission\Models\Role::class)
                ->pluck('model_id')
                ->all()
            : [];

        $rolesViaPivot = DB::table('role_has_permissions')
            ->where('permission_id', $accessRole->id ?? 0)
            ->pluck('role_id')
            ->all();

        $adminRoles = Role::where('name', 'like', 'Admin#%')->pluck('id')->all();

        $candidateRoleIds = array_values(array_unique(array_merge(
            $rolesWithAccess, $rolesViaPivot, $adminRoles
        )));

        if (empty($candidateRoleIds)) return;

        $roles = Role::whereIn('id', $candidateRoleIds)->get();
        foreach ($roles as $role) {
            foreach ($perms as $p) {
                try {
                    $role->givePermissionTo($p);
                } catch (\Throwable $e) {
                    \Log::warning('VetClinic perm backfill skipped for role ' . $role->name . ' / ' . $p->name . ': ' . $e->getMessage());
                }
            }
        }
    }

    public function down()
    {
        // No-op rollback: revoking permissions could lock admins out
        // unexpectedly. The original create migrations remain responsible
        // for the permission rows themselves.
    }
}
