import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { buildContext, confidenceLabel, generateAnswer, type RetrievedChunk } from "@/lib/rag";

export async function POST(request: Request) {
  try {
    const supabase = await createClient();

    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Nie zalogowano." }, { status: 401 });
    }

    const body = await request.json().catch(() => ({}));
    const question = (body?.question || "").trim();
    if (!question) {
      return NextResponse.json({ error: "Podaj pytanie." }, { status: 400 });
    }

    // Wyszukiwanie pełnotekstowe w Postgresie (patrz supabase/schema.sql,
    // funkcja search_chunks) -- odpowiednik retrieve() z lokalnego MVP.
    const { data: results, error: searchError } = await supabase.rpc("search_chunks", {
      query: question,
      match_count: 5,
    });

    if (searchError) {
      return NextResponse.json(
        { error: `Błąd wyszukiwania: ${searchError.message}` },
        { status: 500 }
      );
    }

    const chunks: RetrievedChunk[] = (results || []).map(
      (r: {
        chunk_id: string;
        document_title: string;
        source_file: string;
        paragraph_label: string;
        chunk_text: string;
        rank: number;
      }) => ({
        chunkId: r.chunk_id,
        documentTitle: r.document_title,
        sourceFile: r.source_file,
        paragraphLabel: r.paragraph_label,
        chunkText: r.chunk_text,
        rank: r.rank,
      })
    );

    if (chunks.length === 0) {
      return NextResponse.json({
        answer: "Nie znaleziono pasującego fragmentu w bazie OWU.",
        sources: [],
        confidence: "brak",
        historyId: null,
      });
    }

    const context = buildContext(chunks);
    const answer = await generateAnswer(question, context);
    const confidence = confidenceLabel(chunks[0].rank);

    const sources = chunks.map((c) => ({
      file: c.sourceFile,
      paragraph: c.paragraphLabel,
      score: Math.round(c.rank * 100) / 100,
    }));

    let historyId: string | null = null;
    const { data: historyRow, error: historyError } = await supabase
      .from("history")
      .insert({
        owner_id: user.id,
        question,
        answer,
        sources,
        confidence,
      })
      .select("id")
      .single();
    if (!historyError) {
      historyId = historyRow.id;
    }
    // Błąd zapisu historii nigdy nie powinien wywrócić odpowiedzi dla
    // użytkownika -- podobnie jak w lokalnym MVP (try/except wokół log_query).

    return NextResponse.json({ answer, sources, confidence, historyId });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : String(err);
    return NextResponse.json({ error: `Błąd serwera: ${message}` }, { status: 500 });
  }
}
