<?php

namespace App\Http\Controllers\Api;

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

class LectureViewsController extends Controller
{
    public function viewLecture(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();
        $lectureId = $request->lecture_id;

        $isViewed = LectureViews::where('user_id', $userId)->where('lecture_id', $lectureId)->first();

        if ($isViewed) {
            return sendCustomResponse(false, '', 'This lecture has been viewed before.', '', 422);
        }

        $lecture = Lecture::where('id', $lectureId)->first();

        LectureViews::create([
            'lecture_id' => $lectureId,
            'user_id' => $userId,
            'course_id' => $lecture->course_id
        ]);

        return sendCustomResponse(true, '', 'Lecture has been viewed successfully', '', 200);
    }
}
