<?php

namespace App\Http\Controllers\Api\Administrator;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Teachers\TeacherAssignmentDeleteRequest;
use App\Http\Requests\Teachers\TeacherAssignmentListRequest;
use App\Http\Requests\Teachers\TeacherAssignmentStoreRequest;
use App\Http\Resources\Teachers\TeacherAssignmentResource;
use App\Http\Resources\Teachers\TeacherClassResource;
use App\Services\Teachers\TeacherAssignmentService;
use Illuminate\Http\JsonResponse;

class TeacherClassAssignmentController extends BaseApiController
{
    public function __construct(private TeacherAssignmentService $assignmentService)
    {
        parent::__construct();
    }

    public function index(TeacherAssignmentListRequest $request): JsonResponse
    {
        $data = $this->assignmentService->listAssignments($request->validated()['school_year'] ?? null);

        return response()->json([
            'ok' => true,
            'school_year' => $data['school_year'],
            'teachers' => TeacherAssignmentResource::collection($data['teachers']),
            'classes' => TeacherClassResource::collection($data['classes']),
        ]);
    }

    public function store(TeacherAssignmentStoreRequest $request): JsonResponse
    {
        $userId = $this->authenticatedUserIdOrUnauthorized();
        if ($userId instanceof JsonResponse) {
            return $userId;
        }

        $payload = $request->validated();
        $payload['updated_by'] = $userId;

        $result = $this->assignmentService->assign($payload);
        $status = $result['ok'] ? 200 : 422;

        return response()->json([
            'ok' => (bool) $result['ok'],
            'message' => $result['message'] ?? '',
            'position' => $result['position'] ?? null,
        ], $status);
    }

    public function destroy(TeacherAssignmentDeleteRequest $request): JsonResponse
    {
        $result = $this->assignmentService->delete($request->validated());
        $status = $result['ok'] ? 200 : 422;

        return response()->json([
            'ok' => (bool) $result['ok'],
            'message' => $result['message'] ?? '',
        ], $status);
    }

    /**
     * @return int|JsonResponse
     */
    private function authenticatedUserIdOrUnauthorized(): int|JsonResponse
    {
        $userId = (int) (auth()->id() ?? 0);
        if ($userId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        return $userId;
    }
}
