<?php

namespace App\Http\Controllers\Api\V1\Admin\User;

use App\Models\AdminRole;
use App\Lottery\ErrorCode;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use App\Services\AuditLogger;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Support\AdminRoleApiPresenter;
use App\Support\PlatformSystemRoles;
use App\Http\Requests\Admin\AdminRoleStoreRequest;

final class AdminRoleStoreController extends Controller
{
    public function __invoke(AdminRoleStoreRequest $request): JsonResponse
    {
        $slug = strtolower(trim((string) $request->validated('slug')));
        if (PlatformSystemRoles::isFixedSlug($slug)) {
            return ApiMessage::errorResponse(
                $request,
                'admin.role_slug_reserved',
                ErrorCode::ValidationFailed->value,
                ['slug' => $slug],
                422,
            );
        }

        $role = DB::transaction(function () use ($request, $slug): AdminRole {
            $maxSort = (int) AdminRole::query()
                ->where('scope_type', AdminRole::SCOPE_SYSTEM)
                ->max('sort_order');

            /** @var AdminRole $role */
            $role = AdminRole::query()->create([
                'slug' => $slug,
                'code' => $slug,
                'name' => $request->validated('name'),
                'description' => $request->validated('description'),
                'status' => (int) ($request->validated('status') ?? 1),
                'is_system' => false,
                'sort_order' => max(100, $maxSort + 10),
                'scope_type' => AdminRole::SCOPE_SYSTEM,
                'owner_agent_id' => null,
                'delegated_from_role_id' => null,
            ]);

            $permissionSlugs = $request->validated('permission_slugs', []);
            if (is_array($permissionSlugs) && $permissionSlugs !== []) {
                $role->syncLegacyPermissionSlugs(array_values($permissionSlugs));
            }

            return $role->refresh();
        });

        AuditLogger::recordForAdmin(
            $request->lotteryAdmin(),
            $request,
            'system',
            'admin_role.create',
            'admin_role',
            (string) $role->id,
            null,
            AdminRoleApiPresenter::item($role),
        );

        return ApiResponse::success(AdminRoleApiPresenter::item($role))->setStatusCode(201);
    }
}
