<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ConfidenceScore;
use App\Models\EvaluationSession;
use App\Models\ReviewFlag;
use Illuminate\Http\Request;

/**
 * Read + resolve the integrity engine's output (design §10, §11, §14). Flags
 * are advisory: resolving one is a first-class, encouraged outcome — including
 * "reviewed, looks fine".
 */
class EvaluationIntegrityController extends Controller
{
    /** Open "Review recommended" flags for dashboards. */
    public function flags(Request $request)
    {
        $branchId = $request->header('X-Branch-Id') ?: $request->query('branch_id');
        $flags = ReviewFlag::with(['monthlyEvaluation.schoolClass:id,name', 'monthlyEvaluation.evaluator:id,name'])
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($request->query('status'), fn ($q, $v) => $q->where('status', $v), fn ($q) => $q->where('status', 'open'))
            ->orderByRaw("CASE severity WHEN 'danger' THEN 0 WHEN 'warning' THEN 1 ELSE 2 END")
            ->orderByDesc('created_at')->get();

        return response()->json([
            'data' => $flags,
            'summary' => [
                'total' => $flags->count(),
                'danger' => $flags->where('severity', 'danger')->count(),
                'warning' => $flags->where('severity', 'warning')->count(),
            ],
        ]);
    }

    /** Full integrity view for one evaluation: session + confidence + flags. */
    public function forEvaluation($id)
    {
        return response()->json([
            'session' => EvaluationSession::where('monthly_evaluation_id', $id)->first(),
            'confidence' => ConfidenceScore::where('monthly_evaluation_id', $id)->first(),
            'flags' => ReviewFlag::where('monthly_evaluation_id', $id)->get(),
        ]);
    }

    /** Resolve a flag — reviewed / dismissed, never a penalty. */
    public function resolveFlag(Request $request, $id)
    {
        $flag = ReviewFlag::findOrFail($id);
        $data = $request->validate([
            'status' => 'required|in:reviewed,dismissed,open',
            'note' => 'nullable|string',
        ]);
        $flag->update([
            'status' => $data['status'],
            'resolution_note' => $data['note'] ?? null,
            'resolved_by' => $request->user()?->id,
        ]);

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