<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Lecture;
use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class LectureController extends Controller
{
    private function checkSubscription($course_id)
    {
        $userId = Auth::guard(name: 'sanctum')->id();

        return Subscription::where('user_id', $userId)
            ->where('course_id', $course_id)
            ->whereDate('expires_at', '>', now())
            ->exists();
    }


    public function getLecture(Request $request)
    {
        try {
            $request->validate([
                'lecture_id' => 'required|exists:lectures,id'
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, '', $e->getMessage(), $e->errors(), 422);
        }

        $userId = Auth::guard('sanctum')->id();

        $lecture = Lecture::with(['exam' => function ($query) use ($userId) {
            return $query->withCount(['answer AS is_answered' => function ($row) use ($userId) {
                return $row->where('user_id', $userId);
            }]);
        }])
            ->where('id', $request->lecture_id)->first();

        $courseId = $lecture->course_id;

        $isSubscribed = $this->checkSubscription($courseId);
        if (!$isSubscribed) {
            return sendCustomResponse(false, '', "Sorry, you are not subscribed for this course.", '', 422);
        }

        return sendCustomResponse(true,  $lecture, "", "", 200);
    }
}
