<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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 [];
    }
}
