<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSettlementPermissionAssignments\Pages;

use App\Filament\Resources\DberpSettlementPermissionAssignments\DberpSettlementPermissionAssignmentResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Models\User;
use App\Services\DberpPermissionService;
use DomainException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class EditDberpSettlementPermissionAssignment extends EditRecord
{
    protected static string $resource = DberpSettlementPermissionAssignmentResource::class;

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeFill(array $data): array
    {
        /** @var User $user */
        $user = $this->record;
        $permissionCodes = app(DberpPermissionService::class)->grantedPermissionCodes($user);
        $data['settlement_permission_groups'] = DberpSettlementPermissionAssignmentResource::settlementPermissionGroupsForForm($permissionCodes);

        return $data;
    }

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        /** @var User $record */
        $permissionCodes = DberpSettlementPermissionAssignmentResource::extractSettlementPermissionCodes($data);

        unset($data['settlement_permission_groups']);

        try {
            app(DberpPermissionService::class)->syncPermissions(
                $record,
                $permissionCodes,
                Auth::id(),
                '后台维护结算权限',
            );
        } catch (DomainException $exception) {
            throw ValidationException::withMessages([
                'settlement_permission_groups' => $exception->getMessage(),
            ]);
        }

        return $record->refresh();
    }

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