<?php

namespace App\Http\Controllers\Api\System;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\SchoolIds\SchoolIdAssignRequest;
use App\Http\Resources\SchoolIds\SchoolIdResource;
use App\Services\SchoolIds\SchoolIdAssignmentService;
use App\Services\SchoolIds\SchoolIdGenerationService;
use Illuminate\Http\JsonResponse;

class SchoolIdController extends BaseApiController
{
    public function __construct(
        private SchoolIdAssignmentService $assignmentService,
        private SchoolIdGenerationService $generationService
    ) {
        parent::__construct();
    }

    public function assign(SchoolIdAssignRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $schoolId = $this->assignmentService->assignToUser((int) $payload['user_id']);

        if ($schoolId === null) {
            return response()->json(['ok' => false, 'message' => 'User not found.'], 404);
        }

        return response()->json([
            'ok' => true,
            'result' => new SchoolIdResource([
                'type' => 'user',
                'school_id' => $schoolId,
            ]),
        ]);
    }

    public function generateStudent(): JsonResponse
    {
        $schoolId = $this->generationService->generateStudentId();

        return response()->json([
            'ok' => true,
            'result' => new SchoolIdResource([
                'type' => 'student',
                'school_id' => $schoolId,
            ]),
        ]);
    }

    public function generateUser(): JsonResponse
    {
        $schoolId = $this->generationService->generateUserId();

        return response()->json([
            'ok' => true,
            'result' => new SchoolIdResource([
                'type' => 'user',
                'school_id' => $schoolId,
            ]),
        ]);
    }
}
