<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpAdminUsers\Pages;

use App\Filament\Resources\DberpAdminUsers\DberpAdminUserResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Models\User;
use App\Services\DberpAdminAccessService;
use DomainException;
use Filament\Actions\DeleteAction;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class EditDberpAdminUser extends EditRecord
{
    protected static string $resource = DberpAdminUserResource::class;

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeFill(array $data): array
    {
        $data['role_ids'] = $this->record->adminRoles()
            ->orderBy('sort_order')
            ->orderBy('id')
            ->pluck('core_roles.id')
            ->map(fn (mixed $roleId): int => (int) $roleId)
            ->all();

        return $data;
    }

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        if (! $record instanceof User) {
            throw ValidationException::withMessages([
                'login_account' => '当前记录类型不支持管理员编辑。',
            ]);
        }

        $roleIds = collect($data['role_ids'] ?? [])
            ->map(fn (mixed $roleId): int => (int) $roleId)
            ->all();

        unset($data['role_ids'], $data['password_confirmation']);

        try {
            return app(DberpAdminAccessService::class)->updateUser(
                $record,
                $data,
                $roleIds,
                Auth::user(),
                '管理员管理页编辑管理员',
            );
        } catch (AuthorizationException $exception) {
            throw ValidationException::withMessages([
                'login_account' => $exception->getMessage(),
            ]);
        } catch (DomainException $exception) {
            $message = $exception->getMessage();

            if ($message === (string) __('dberp.errors.bootstrap_admin_roles_locked')) {
                throw ValidationException::withMessages([
                    'role_ids' => $message,
                ]);
            }

            $field = str_contains($message, '邮箱') ? 'email' : 'login_account';

            throw ValidationException::withMessages([
                $field => $message,
            ]);
        }
    }

    protected function getHeaderActions(): array
    {
        return [
            DeleteAction::make()
                ->label(__('dberp.actions.delete'))
                ->visible(fn (): bool => $this->getRecord() instanceof User && DberpAdminUserResource::canDelete($this->getRecord()))
                ->using(DberpAdminUserResource::deleteAdminUserUsing()),
        ];
    }
}
