<?php

namespace App\Http\Controllers\Api\Assessment;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AssessmentSubmission;
use App\Models\AssessmentAnswer;

class AssessmentSubmissionController extends Controller
{
    // 🔹 start assessment
    public function start(Request $request)
    {
        $data = $request->validate([
            'assessment_id' => 'required',
            'application_id' => 'required'
        ]);

        $data['jobseeker_id'] = auth()->user()->jobseeker->id;
        $data['status'] = 'in-progress';
        $data['started_at'] = now();

        return AssessmentSubmission::create($data);
    }

    // 🔹 submit answer
    public function submitAnswer(Request $request)
    {
        $data = $request->validate([
            'submission_id' => 'required',
            'question_id' => 'required',
            'answer_text' => 'nullable'
        ]);

        return AssessmentAnswer::updateOrCreate(
            [
                'submission_id' => $request->submission_id,
                'question_id' => $request->question_id
            ],
            $data
        );
    }

    // 🔹 finish assessment
    public function finish($id)
    {
        $submission = AssessmentSubmission::findOrFail($id);

        // 🔥 simple scoring (bisa kamu upgrade nanti)
        $answers = AssessmentAnswer::where('submission_id',$id)->get();

        $score = $answers->sum('points_earned');

        $submission->update([
            'status' => 'completed',
            'score' => $score,
            'submitted_at' => now()
        ]);

        return $submission;
    }

    // 🔹 result
    public function show($id)
    {
        return AssessmentSubmission::with([
            'assessment',
            'answers'
        ])->findOrFail($id);
    }
}