import { NextResponse } from "next/server";
import { authenticateDeveloperRequest } from "@/lib/developers/auth";
import { emitWorkspaceWebhookEvent } from "@/lib/developers/webhooks";
import { logProjectActivity } from "@/lib/project-activity";
import { logTeamAudit } from "@/lib/team-audit";
import { sql } from "@/lib/db/postgres";
import type { Note } from "@/types";

async function loadOwnedNote(
  id: string,
  workspaceUserId: string,
  workspaceTeamId: string | null
) {
  const { rows } = workspaceTeamId
    ? await sql<Note>`SELECT * FROM notes WHERE id = ${id} AND team_id = ${workspaceTeamId} LIMIT 1`
    : await sql<Note>`SELECT * FROM notes WHERE id = ${id} AND team_id IS NULL AND user_id = ${workspaceUserId} LIMIT 1`;
  return rows[0] ?? null;
}

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

  const { id } = await context.params;
  const note = await loadOwnedNote(id, auth.workspaceUserId, auth.workspaceTeamId);
  if (!note) return NextResponse.json({ error: "Note not found" }, { status: 404 });

  return NextResponse.json({ note });
}

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

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

  const body = await req.json();
  const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : current.title;
  const content =
    body.content && typeof body.content === "object" && !Array.isArray(body.content)
      ? body.content
      : current.content;
  const folder_id = body.folder_id !== undefined ? (typeof body.folder_id === "string" ? body.folder_id : null) : current.folder_id;
  const project_id = body.project_id !== undefined ? (typeof body.project_id === "string" ? body.project_id : null) : current.project_id;
  const is_pinned = typeof body.is_pinned === "boolean" ? body.is_pinned : current.is_pinned;

  const { rows } = await sql<Note>`
    UPDATE notes SET
      title = ${title},
      content = ${JSON.stringify(content)},
      folder_id = ${folder_id},
      project_id = ${project_id},
      is_pinned = ${is_pinned}
    WHERE id = ${id}
    RETURNING *
  `;
  const note = rows[0];

  await logProjectActivity(auth.admin, {
    userId: auth.workspaceUserId,
    projectId: note.project_id,
    entityType: "note",
    entityId: note.id,
    action: "note_updated",
    title: note.title,
  });
  await logTeamAudit(auth.admin, {
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    action: "note_updated",
    entityType: "note",
    entityId: note.id,
    title: note.title,
  });
  await emitWorkspaceWebhookEvent({
    userId: auth.workspaceUserId,
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    eventType: "note.updated",
    data: { note, source: "developer_api" },
  });

  return NextResponse.json({ note });
}

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

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

  await sql`DELETE FROM notes WHERE id = ${id}`;

  await logTeamAudit(auth.admin, {
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    action: "note_deleted",
    entityType: "note",
    entityId: current.id,
    title: current.title,
  });
  await emitWorkspaceWebhookEvent({
    userId: auth.workspaceUserId,
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    eventType: "note.deleted",
    data: { note: { id: current.id, title: current.title }, source: "developer_api" },
  });

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