<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\CourseResource;
use App\Models\Course;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Auth;

class CourseAPIController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $cacheKey = 'courses';
        $expirationTime = 60;

        if (Redis::exists($cacheKey)) {
            $courses = json_decode(Redis::get($cacheKey));
        } else {
            $courses = Course::with('category', 'status', 'language', 'instructor', 'level')->get();
            Redis::set($cacheKey, json_encode($courses));
            Redis::expire($cacheKey, $expirationTime);
        }

        return CourseResource::collection($courses);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $courses = Course::find($id);
        $usr = Auth::user();
        $user = User::find($usr->id);

        $courses->isPurchased = !empty($user->enrollments) ? $user->enrollments->contains($id) : false; 

        return new CourseResource($courses);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
