import { NextResponse } from "next/server";
import { authenticateDeveloperRequest } from "@/lib/developers/auth";
import { sql } from "@/lib/db/postgres";
import type { JournalEntry, Mood } from "@/types";

async function loadOwnedEntry(id: string, workspaceUserId: string) {
  const { rows } = await sql<JournalEntry>`
    SELECT * FROM journal_entries WHERE id = ${id} AND user_id = ${workspaceUserId} LIMIT 1
  `;
  return rows[0] ?? null;
}

export async function PATCH(req: Request, context: { params: Promise<{ id: string }> }) {
  const auth = await authenticateDeveloperRequest(req, { write: true, section: "journal" });
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await context.params;
  const current = await loadOwnedEntry(id, auth.workspaceUserId);
  if (!current) return NextResponse.json({ error: "Journal entry not found" }, { status: 404 });

  const body = await req.json();
  const title = typeof body.title === "string" ? body.title : current.title;
  const content =
    body.content && typeof body.content === "object" && !Array.isArray(body.content)
      ? body.content
      : current.content;
  const mood: Mood | null =
    body.mood === "great" || body.mood === "good" || body.mood === "neutral" || body.mood === "bad" || body.mood === "terrible"
      ? body.mood
      : body.mood === null
      ? null
      : current.mood;
  const completed = typeof body.completed === "boolean" ? body.completed : current.completed;

  const { rows } = await sql<JournalEntry>`
    UPDATE journal_entries SET
      title = ${title},
      content = ${JSON.stringify(content)},
      mood = ${mood},
      completed = ${completed}
    WHERE id = ${id}
    RETURNING *
  `;

  return NextResponse.json({ entry: rows[0] });
}

export async function DELETE(req: Request, context: { params: Promise<{ id: string }> }) {
  const auth = await authenticateDeveloperRequest(req, { write: true, section: "journal" });
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await context.params;
  const current = await loadOwnedEntry(id, auth.workspaceUserId);
  if (!current) return NextResponse.json({ error: "Journal entry not found" }, { status: 404 });

  await sql`DELETE FROM journal_entries WHERE id = ${id}`;
  return NextResponse.json({ success: true });
}
