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";

export async function GET(req: Request) {
  const auth = await authenticateDeveloperRequest(req, { section: "notes" });
  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") || 50), 1), 100);
  const projectId = url.searchParams.get("projectId");
  const folderId = url.searchParams.get("folderId");

  let notes: Record<string, unknown>[];

  if (auth.workspaceTeamId) {
    if (projectId && folderId) {
      const { rows } = await sql`
        SELECT * FROM notes
        WHERE team_id = ${auth.workspaceTeamId}
          AND project_id = ${projectId}
          AND folder_id = ${folderId}
        ORDER BY updated_at DESC
        LIMIT ${limit}
      `;
      notes = rows;
    } else if (projectId) {
      const { rows } = await sql`
        SELECT * FROM notes
        WHERE team_id = ${auth.workspaceTeamId}
          AND project_id = ${projectId}
        ORDER BY updated_at DESC
        LIMIT ${limit}
      `;
      notes = rows;
    } else if (folderId) {
      const { rows } = await sql`
        SELECT * FROM notes
        WHERE team_id = ${auth.workspaceTeamId}
          AND folder_id = ${folderId}
        ORDER BY updated_at DESC
        LIMIT ${limit}
      `;
      notes = rows;
    } else {
      const { rows } = await sql`
        SELECT * FROM notes
        WHERE team_id = ${auth.workspaceTeamId}
        ORDER BY updated_at DESC
        LIMIT ${limit}
      `;
      notes = rows;
    }
  } else {
    if (projectId && folderId) {
      const { rows } = await sql`
        SELECT * FROM notes
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND project_id = ${projectId}
          AND folder_id = ${folderId}
        ORDER BY updated_at DESC
        LIMIT ${limit}
      `;
      notes = rows;
    } else if (projectId) {
      const { rows } = await sql`
        SELECT * FROM notes
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND project_id = ${projectId}
        ORDER BY updated_at DESC
        LIMIT ${limit}
      `;
      notes = rows;
    } else if (folderId) {
      const { rows } = await sql`
        SELECT * FROM notes
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND folder_id = ${folderId}
        ORDER BY updated_at DESC
        LIMIT ${limit}
      `;
      notes = rows;
    } else {
      const { rows } = await sql`
        SELECT * FROM notes
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
        ORDER BY updated_at DESC
        LIMIT ${limit}
      `;
      notes = rows;
    }
  }

  return NextResponse.json({ notes });
}

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

  const body = await req.json();

  const title =
    typeof body.title === "string" && body.title.trim()
      ? body.title.trim()
      : "Untitled";
  const content =
    body.content && typeof body.content === "object" && !Array.isArray(body.content)
      ? body.content
      : {};
  const folder_id = typeof body.folder_id === "string" ? body.folder_id : null;
  const project_id = typeof body.project_id === "string" ? body.project_id : null;
  const linked_task_id = typeof body.linked_task_id === "string" ? body.linked_task_id : null;

  let data: Record<string, unknown>;
  try {
    const { rows } = await sql`
      INSERT INTO notes (user_id, team_id, title, content, folder_id, project_id, linked_task_id)
      VALUES (
        ${auth.workspaceUserId},
        ${auth.workspaceTeamId},
        ${title},
        ${JSON.stringify(content)},
        ${folder_id},
        ${project_id},
        ${linked_task_id}
      )
      RETURNING *
    `;
    data = rows[0];
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Note could not be created";
    return NextResponse.json({ error: msg }, { status: 400 });
  }

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

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