<?php

namespace App\Http\Controllers;

use App\Models\Vocabulary;
use App\Models\SrsReview;
use App\Services\SrsService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SrsController extends Controller
{
    protected $srsService;

    public function __construct(SrsService $srsService)
    {
        $this->srsService = $srsService;
    }

    public function index()
    {
        $user = auth()->user();
        $dueCount = $this->srsService->getDueReviews($user, 1000)->count();
        $newCount = $this->srsService->getNewCards($user, 1000)->count();

        return Inertia::render('Srs/Index', [
            'stats' => [
                'due' => $dueCount,
                'new' => $newCount,
                'total_learned' => SrsReview::where('user_id', $user->id)->count()
            ]
        ]);
    }

    public function practice()
    {
        $user = auth()->user();
        
        $reviews = $this->srsService->getDueReviews($user, 20);
        
        // If Reviews < 10, fill with New Cards
        $newCards = $reviews->count() < 10 
            ? $this->srsService->getNewCards($user, 10 - $reviews->count()) 
            : collect([]);

        // Normalize items for frontend
        $items = $reviews->toBase()->map(function($review) {
            return [
                'type' => 'review',
                'id' => $review->vocabulary->id,
                'word' => $review->vocabulary->word,
                'reading' => $review->vocabulary->reading,
                'meaning' => $review->vocabulary->meaning_en,
                'audio_url' => $review->vocabulary->audio_url,
                'srs_id' => $review->id
            ];
        })->merge($newCards->toBase()->map(function($vocab) {
            return [
                'type' => 'new',
                'id' => $vocab->id,
                'word' => $vocab->word,
                'reading' => $vocab->reading,
                'meaning' => $vocab->meaning_en,
                'audio_url' => $vocab->audio_url,
            ];
        }));

        return Inertia::render('Srs/Practice', [
            'items' => $items
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'vocabulary_id' => 'required|exists:vocabularies,id',
            'grade' => 'required|integer|min:1|max:4' // 1=Again, 2=Hard, 3=Good, 4=Easy
        ]);

        $user = auth()->user();
        $vocab = Vocabulary::find($request->vocabulary_id);

        $this->srsService->processReview($user, $vocab, $request->grade);

        if ($request->wantsJson()) {
            return response()->json(['status' => 'success']);
        }

        return back();
    }
}
