import { NextResponse } from "next/server";
import { authenticateDeveloperRequest } from "@/lib/developers/auth";
import { query } from "@/lib/db/postgres";
import { logApiError } from "@/lib/api/security";

// GET /api/v1/vault/documents?q=&entity_type=&limit=&offset=
// Vault = documents attached to tasks, notes, projects and invoices. Read-only through the API:
// returns metadata only (name, type, size, date, linked item) – no file contents, no download links.
export async function GET(req: Request) {
  const auth = await authenticateDeveloperRequest(req, { section: "vault" });
  if (!auth) {
    return NextResponse.json({ error: "Unauthorized – token needs the 'Vault' right (Mindavio → Developers)" }, { status: 401 });
  }

  const url = new URL(req.url);
  const where: string[] = [];
  const values: (string | number)[] = [];
  const add = (clause: string, value: string | number) => {
    values.push(value);
    where.push(clause.replace("?", `$${values.length}`));
  };

  if (auth.workspaceTeamId) add("a.team_id = ?", auth.workspaceTeamId);
  else {
    where.push("a.team_id IS NULL");
    add("a.user_id = ?", auth.workspaceUserId);
  }
  const q = url.searchParams.get("q");
  if (q) add("a.file_name ILIKE ?", `%${q.slice(0, 100).replace(/[%_\\]/g, (c) => `\\${c}`)}%`);
  const entityType = url.searchParams.get("entity_type");
  if (entityType) {
    if (!["project", "task", "note", "invoice"].includes(entityType)) {
      return NextResponse.json({ error: "entity_type must be project, task, note or invoice" }, { status: 400 });
    }
    add("a.entity_type = ?", entityType);
  }
  const limit = Math.min(Math.max(Number(url.searchParams.get("limit") || 100) || 100, 1), 200);
  const offset = Math.max(Number(url.searchParams.get("offset") || 0) || 0, 0);

  try {
    const { rows } = await query(
      `SELECT a.id, a.file_name, a.mime_type, a.size_bytes, a.entity_type, a.entity_id, a.project_id, a.created_at,
              COALESCE(t.title, n.title, p.name) AS linked_title
       FROM attachments a
       LEFT JOIN tasks t ON a.entity_type = 'task' AND t.id = a.entity_id
       LEFT JOIN notes n ON a.entity_type = 'note' AND n.id = a.entity_id
       LEFT JOIN projects p ON a.entity_type = 'project' AND p.id = a.entity_id
       WHERE ${where.join(" AND ")}
       ORDER BY a.created_at DESC
       LIMIT ${limit} OFFSET ${offset}`,
      values
    );
    return NextResponse.json({ documents: rows, limit, offset });
  } catch (error) {
    logApiError("Vault documents GET error", error);
    return NextResponse.json({ error: "Vault request failed" }, { status: 500 });
  }
}
