<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpAdminRoles\Pages;

use App\Filament\Resources\DberpAdminRoles\DberpAdminRoleResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Models\DberpAdminRole;
use App\Services\DberpAdminAccessService;
use App\Services\DberpPermissionRegistry;
use DomainException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class EditDberpAdminRole extends EditRecord
{
    protected static string $resource = DberpAdminRoleResource::class;

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeFill(array $data): array
    {
        if ($this->record instanceof DberpAdminRole) {
            $permissionCodes = $this->record->is_super_admin
                ? app(DberpPermissionRegistry::class)->codes()
                : $this->record->permissions()
                    ->orderBy('sort_order')
                    ->pluck('core_permissions.name')
                    ->all();

            $data['permission_groups'] = DberpAdminRoleResource::permissionGroupsForForm($permissionCodes);
        }

        return $data;
    }

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        if (! $record instanceof DberpAdminRole) {
            throw ValidationException::withMessages([
                'display_name' => (string) __('dberp.errors.admin_role_record_invalid'),
            ]);
        }

        $permissionCodes = DberpAdminRoleResource::extractPermissionCodes($data);
        $permissionCodes = DberpAdminRoleResource::mergeRoleIntegrationPermissionSelections($record, $permissionCodes);

        unset($data['permission_groups']);

        try {
            return app(DberpAdminAccessService::class)->updateRole(
                $record,
                $data,
                $permissionCodes,
                Auth::user(),
                (string) __('dberp.messages.audit_remark_admin_role_updated'),
            );
        } catch (AuthorizationException|DomainException $exception) {
            throw ValidationException::withMessages([
                'display_name' => $exception->getMessage(),
            ]);
        }
    }

    protected function getHeaderActions(): array
    {
        return [];
    }
}
