import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";

export async function POST(request: Request) {
  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 id = body?.id as string | undefined;
  const value = body?.value as "up" | "down" | null | undefined;

  if (!id || (value !== "up" && value !== "down" && value !== null)) {
    return NextResponse.json({ error: "Nieprawidłowe dane." }, { status: 400 });
  }

  // Uwaga: przy update() `.select()` zwraca zaktualizowane wiersze, ale nie
  // przyjmuje opcji `{ count }` (to działa tylko przy .from().select() do
  // odczytu) -- więc o istnieniu wpisu wnioskujemy z długości `data`.
  const { data, error } = await supabase
    .from("history")
    .update({ feedback: value })
    .eq("id", id)
    .eq("owner_id", user.id)
    .select("id");

  if (error) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
  if (!data || data.length === 0) {
    return NextResponse.json({ error: "Nie znaleziono wpisu." }, { status: 404 });
  }

  return NextResponse.json({ ok: true });
}
