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

// Journal entries have no team dimension today — they always belong to the
// token's own user, regardless of which workspace the token was issued for.

export async function GET(req: Request) {
  const auth = await authenticateDeveloperRequest(req, { section: "journal" });
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const url = new URL(req.url);
  const limit = Math.min(Math.max(Number(url.searchParams.get("limit") || 30), 1), 100);
  const date = url.searchParams.get("date");

  const { rows } = date
    ? await sql<JournalEntry>`
        SELECT * FROM journal_entries
        WHERE user_id = ${auth.workspaceUserId} AND entry_date = ${date}
        LIMIT ${limit}
      `
    : await sql<JournalEntry>`
        SELECT * FROM journal_entries
        WHERE user_id = ${auth.workspaceUserId}
        ORDER BY entry_date DESC
        LIMIT ${limit}
      `;

  return NextResponse.json({ entries: rows });
}

export async function POST(req: Request) {
  const auth = await authenticateDeveloperRequest(req, { write: true, section: "journal" });
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json();
  const entry_date =
    typeof body.entry_date === "string" && body.entry_date
      ? body.entry_date
      : new Date().toISOString().slice(0, 10);
  const title = typeof body.title === "string" ? body.title : "";
  const content =
    body.content && typeof body.content === "object" && !Array.isArray(body.content) ? body.content : {};
  const mood: Mood | null =
    body.mood === "great" || body.mood === "good" || body.mood === "neutral" || body.mood === "bad" || body.mood === "terrible"
      ? body.mood
      : null;
  const completed = typeof body.completed === "boolean" ? body.completed : false;

  // Upsert by (user_id, entry_date) — mirrors getOrCreateEntry in the app UI
  // so "create today's journal entry" through the API behaves the same way.
  const { rows: existingRows } = await sql<JournalEntry>`
    SELECT id FROM journal_entries WHERE user_id = ${auth.workspaceUserId} AND entry_date = ${entry_date} LIMIT 1
  `;

  let entry: JournalEntry;
  if (existingRows[0]) {
    const { rows } = await sql<JournalEntry>`
      UPDATE journal_entries SET
        title = ${title},
        content = ${JSON.stringify(content)},
        mood = ${mood},
        completed = ${completed}
      WHERE id = ${existingRows[0].id}
      RETURNING *
    `;
    entry = rows[0];
  } else {
    const { rows } = await sql<JournalEntry>`
      INSERT INTO journal_entries (user_id, entry_date, title, content, mood, completed)
      VALUES (${auth.workspaceUserId}, ${entry_date}, ${title}, ${JSON.stringify(content)}, ${mood}, ${completed})
      RETURNING *
    `;
    entry = rows[0];
  }

  return NextResponse.json({ entry }, { status: 201 });
}
