<?php

namespace App\Http\Controllers;

use App\Models\RiskAssessment;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class RiskAssessmentController extends Controller
{
    public function index(Request $request)
    {
        $query = RiskAssessment::query()->with(['project', 'assignee'])->latest();

        if ($request->filled('project_id')) {
            $query->where('project_id', $request->project_id);
        }

        $risks = $query->get();

        return response()->json([
            'data' => $risks,
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'project_id' => 'required|exists:projects,id',
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'risk_level' => ['nullable', Rule::in(['low', 'medium', 'high', 'critical'])],
            'status' => ['nullable', Rule::in(['open', 'mitigating', 'resolved'])],
            'mitigation_plan' => 'nullable|string',
            'identified_date' => 'nullable|date',
            'resolved_date' => 'nullable|date|after_or_equal:identified_date',
            'assigned_to_id' => 'nullable|exists:users,id',
            'likelihood' => ['nullable', Rule::in(['low', 'medium', 'high'])],
            'impact' => ['nullable', Rule::in(['low', 'medium', 'high'])],
        ]);

        $riskLevel = $request->risk_level ?? $this->deriveRiskLevel($request->likelihood, $request->impact);

        $risk = RiskAssessment::create([
            'project_id' => $request->project_id,
            'title' => $request->title,
            'description' => $request->description,
            'risk_level' => $riskLevel,
            'status' => $request->status ?? 'open',
            'mitigation_plan' => $request->mitigation_plan,
            'identified_date' => $request->identified_date ?? now()->toDateString(),
            'resolved_date' => $request->resolved_date,
            'assigned_to_id' => $request->assigned_to_id,
            'likelihood' => $request->likelihood,
            'impact' => $request->impact,
        ]);

        $risk->load(['project', 'assignee']);

        return response()->json([
            'data' => $risk,
        ], 201);
    }

    public function show($id)
    {
        $risk = RiskAssessment::with(['project', 'assignee'])->find($id);

        if (!$risk) {
            return response()->json(['message' => 'Risk assessment not found'], 404);
        }

        return response()->json([
            'data' => $risk,
        ]);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'project_id' => 'nullable|exists:projects,id',
            'title' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'risk_level' => ['nullable', Rule::in(['low', 'medium', 'high', 'critical'])],
            'status' => ['nullable', Rule::in(['open', 'mitigating', 'resolved'])],
            'mitigation_plan' => 'nullable|string',
            'identified_date' => 'nullable|date',
            'resolved_date' => 'nullable|date|after_or_equal:identified_date',
            'assigned_to_id' => 'nullable|exists:users,id',
            'likelihood' => ['nullable', Rule::in(['low', 'medium', 'high'])],
            'impact' => ['nullable', Rule::in(['low', 'medium', 'high'])],
        ]);

        $risk = RiskAssessment::find($id);

        if (!$risk) {
            return response()->json(['message' => 'Risk assessment not found'], 404);
        }

        $risk->update($request->only([
            'project_id',
            'title',
            'description',
            'risk_level',
            'status',
            'mitigation_plan',
            'identified_date',
            'resolved_date',
            'assigned_to_id',
            'likelihood',
            'impact',
        ]));

        $risk->load(['project', 'assignee']);

        return response()->json([
            'data' => $risk,
        ]);
    }

    public function destroy($id)
    {
        $risk = RiskAssessment::find($id);

        if (!$risk) {
            return response()->json(['message' => 'Risk assessment not found'], 404);
        }

        $risk->delete();

        return response()->json([
            'message' => 'Risk assessment deleted successfully',
        ]);
    }

    private function deriveRiskLevel(?string $likelihood, ?string $impact): string
    {
        $map = [
            'low' => 1,
            'medium' => 2,
            'high' => 3,
        ];

        if (!$likelihood || !$impact) {
            return 'medium';
        }

        $score = ($map[$likelihood] ?? 2) + ($map[$impact] ?? 2);

        if ($score >= 6) {
            return 'critical';
        }

        if ($score >= 5) {
            return 'high';
        }

        if ($score >= 3) {
            return 'medium';
        }

        return 'low';
    }
}
