<?php

namespace App\Http\Controllers;

use App\Models\Inspection;
use App\Models\Opportunity;
use App\Services\Inspection\InspectionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class InspectionController extends Controller
{
    public function __construct(
        private InspectionService $inspectionService
    ) {}

    public function start(Request $request)
    {
        $request->validate([
            'type' => 'required|in:buy,sell',
            'ad_id' => 'nullable|exists:opportunities,id',
        ]);

        $type = $request->input('type');
        $adId = $request->input('ad_id');

        $ad = $adId ? Opportunity::find($adId) : null;

        $inspection = $this->inspectionService->startInspection(
            Auth::user(),
            $type,
            $ad
        );

        return response()->json([
            'inspection_id' => $inspection->id,
            'questions' => $this->inspectionService->getQuestions($type),
            'total_questions' => $this->inspectionService->getTotalQuestions($type),
        ]);
    }

    public function answer(Request $request, Inspection $inspection)
    {
        $request->validate([
            'answer' => 'required|string',
        ]);

        // Check if user owns this inspection
        if ($inspection->user_id !== Auth::id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        // Check if inspection is still in progress
        if (!$inspection->isInProgress()) {
            return response()->json(['error' => 'Inspection is not in progress'], 400);
        }

        $answer = $request->input('answer');
        $updatedInspection = $this->inspectionService->answerQuestion($inspection, $answer);

        // Check if inspection is complete
        if ($this->inspectionService->isInspectionComplete($updatedInspection)) {
            $completedInspection = $this->inspectionService->completeInspection($updatedInspection);

            return response()->json([
                'inspection' => $completedInspection,
                'is_complete' => true,
                'risk_score' => $completedInspection->risk_score,
                'risk_level' => $completedInspection->risk_level,
                'recommendations' => $completedInspection->recommendations,
            ]);
        }

        // Get next question
        $nextQuestion = $this->inspectionService->getNextQuestion($updatedInspection);
        $progress = $this->inspectionService->getProgress($updatedInspection);

        return response()->json([
            'inspection' => $updatedInspection,
            'is_complete' => false,
            'next_question' => $nextQuestion,
            'progress' => $progress,
        ]);
    }

    public function show(Inspection $inspection)
    {
        // Check if user owns this inspection
        if ($inspection->user_id !== Auth::id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        return response()->json($inspection);
    }

    public function progress(Inspection $inspection)
    {
        // Check if user owns this inspection
        if ($inspection->user_id !== Auth::id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $progress = $this->inspectionService->getProgress($inspection);
        $nextQuestion = $this->inspectionService->getNextQuestion($inspection);

        return response()->json([
            'inspection' => $inspection,
            'progress' => $progress,
            'next_question' => $nextQuestion,
        ]);
    }

    public function cancel(Inspection $inspection)
    {
        // Check if user owns this inspection
        if ($inspection->user_id !== Auth::id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        // Check if inspection is still in progress
        if (!$inspection->isInProgress()) {
            return response()->json(['error' => 'Inspection is not in progress'], 400);
        }

        $inspection->update([
            'status' => 'cancelled',
        ]);

        return response()->json([
            'message' => 'Inspection cancelled successfully',
            'inspection' => $inspection,
        ]);
    }
}
