<?php

declare(strict_types=1);

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()),
        ];
    }
}
