/**
 * Public REST API conventions (BRD §11):
 * - Auth: scoped API keys (Authorization: Bearer tp_…) or the user's session cookie
 * - Idempotency-Key header honoured on POST
 * - Rate limits per key in X-RateLimit-* headers; 429 on breach
 * - Errors: { "error": { "code", "message", "details" } }
 * - Cursor pagination (?cursor=&limit=), filtering (?filter[stage]=won), ISO 8601 UTC dates
 */
import { NextResponse, type NextRequest } from "next/server";
import { after } from "next/server";
import { and, eq, isNull, sql } from "drizzle-orm";
import { ZodError, type ZodTypeAny, type output } from "zod";
import { getDb, schema } from "@/db";
import { getCtx, type Ctx } from "./auth";
import { can, SCOPE_TO_CAP, type ApiScope } from "./rbac";
import { sha256 } from "./util";
import { runJobs } from "./jobs";

export class ApiError extends Error {
  constructor(public status: number, public code: string, message: string, public details?: unknown) {
    super(message);
  }
}
export const notFound = (what = "Resource") => new ApiError(404, "not_found", `${what} not found`);
export const forbidden = (msg = "You do not have permission for this action") => new ApiError(403, "forbidden", msg);
export const badRequest = (msg: string, details?: unknown) => new ApiError(400, "bad_request", msg, details);

const RATE_LIMIT = Number(process.env.API_RATE_LIMIT_PER_MIN ?? 600);

async function rateLimit(bucket: string, limit = RATE_LIMIT, windowMs = 60000) {
  const db = await getDb();
  const now = new Date();
  const rows = await db.insert(schema.rateLimits).values({ bucket, count: 1, windowStart: now })
    .onConflictDoUpdate({
      target: schema.rateLimits.bucket,
      set: {
        count: sql`CASE WHEN ${schema.rateLimits.windowStart} < ${new Date(now.getTime() - windowMs)} THEN 1 ELSE ${schema.rateLimits.count} + 1 END`,
        windowStart: sql`CASE WHEN ${schema.rateLimits.windowStart} < ${new Date(now.getTime() - windowMs)} THEN ${now} ELSE ${schema.rateLimits.windowStart} END`,
      },
    }).returning();
  const r = rows[0]!;
  const reset = Math.ceil((r.windowStart.getTime() + windowMs) / 1000);
  return { ok: r.count <= limit, remaining: Math.max(0, limit - r.count), limit, reset };
}
export { rateLimit };

export async function ctxFromApiKey(req: NextRequest): Promise<Ctx | null> {
  const auth = req.headers.get("authorization");
  if (!auth?.startsWith("Bearer ")) return null;
  const raw = auth.slice(7).trim();
  const db = await getDb();
  const key = await db.query.apiKeys.findFirst({ where: and(eq(schema.apiKeys.hashedKey, sha256(raw)), isNull(schema.apiKeys.revokedAt)) });
  if (!key) throw new ApiError(401, "unauthorized", "Invalid or revoked API key");
  const workspace = await db.query.workspaces.findFirst({ where: eq(schema.workspaces.id, key.workspaceId) });
  if (!workspace) throw new ApiError(401, "unauthorized", "Workspace not found");
  db.update(schema.apiKeys).set({ lastUsedAt: new Date() }).where(eq(schema.apiKeys.id, key.id)).catch(() => {});
  const { DEFAULT_ROLES } = await import("./rbac");
  return {
    db, workspace, user: null,
    perms: DEFAULT_ROLES[1]!.permissions, roleKey: "api_key", roleName: `API key: ${key.name}`,
    actor: { type: "api_key", id: key.id, name: key.name }, scopes: key.scopes,
    ip: req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
  };
}

/** ADM-007: a key limited to read:contacts cannot write. Session users are checked against their role. */
export function requireScope(ctx: Ctx, scope: ApiScope) {
  if (ctx.scopes) {
    if (ctx.scopes.includes("admin") || ctx.scopes.includes(scope)) return;
    throw forbidden(`API key is missing scope ${scope}`);
  }
  const [cap, need] = SCOPE_TO_CAP[scope] ?? ["admin", "edit"];
  if (!can(ctx.perms, cap, need)) throw forbidden();
}

type Handler<P> = (req: NextRequest, ctx: Ctx, params: P) => Promise<unknown>;

export function api<P = Record<string, string>>(opts: { scope?: ApiScope }, handler: Handler<P>) {
  return async (req: NextRequest, route: { params: Promise<P> }) => {
    const headers: Record<string, string> = {};
    try {
      const ctx = (await ctxFromApiKey(req)) ?? (await getCtx());
      if (!ctx) throw new ApiError(401, "unauthorized", "Authentication required");
      const rl = await rateLimit(`api:${ctx.actor.type}:${ctx.actor.id ?? ctx.workspace.id}`);
      Object.assign(headers, { "X-RateLimit-Limit": String(rl.limit), "X-RateLimit-Remaining": String(rl.remaining), "X-RateLimit-Reset": String(rl.reset) });
      if (!rl.ok) throw new ApiError(429, "rate_limited", "Rate limit exceeded");
      if (opts.scope) requireScope(ctx, opts.scope);

      const idem = req.method === "POST" ? req.headers.get("idempotency-key") : null;
      const idemKey = idem ? `${ctx.workspace.id}:${sha256(req.nextUrl.pathname + ":" + idem)}` : null;
      if (idemKey) {
        const prev = await ctx.db.query.idempotencyKeys.findFirst({ where: eq(schema.idempotencyKeys.key, idemKey) });
        if (prev) return NextResponse.json(prev.response, { status: prev.statusCode, headers: { ...headers, "Idempotent-Replayed": "true" } });
      }
      const params = (await route.params) ?? ({} as P);
      const result = await handler(req, ctx, params);
      after(() => runJobs(10, 8000).catch(() => {}));
      if (result instanceof Response) return result;
      const status = req.method === "POST" ? 201 : 200;
      const body = result === undefined ? { ok: true } : result;
      if (idemKey) await ctx.db.insert(schema.idempotencyKeys).values({ key: idemKey, response: body as object, statusCode: status }).onConflictDoNothing();
      return NextResponse.json(body, { status, headers });
    } catch (e) {
      return errorResponse(e, headers);
    }
  };
}

export function errorResponse(e: unknown, headers: Record<string, string> = {}) {
  if (e instanceof ApiError) return NextResponse.json({ error: { code: e.code, message: e.message, details: e.details ?? null } }, { status: e.status, headers });
  if (e instanceof ZodError) return NextResponse.json({ error: { code: "validation_failed", message: "Request body failed validation", details: e.flatten() } }, { status: 422, headers });
  console.error("[api] unhandled", e);
  return NextResponse.json({ error: { code: "internal", message: "Internal server error", details: null } }, { status: 500, headers });
}

export async function body<S extends ZodTypeAny>(req: NextRequest, schemaDef: S): Promise<output<S>> {
  let json: unknown;
  try {
    json = await req.json();
  } catch {
    throw badRequest("Body must be valid JSON");
  }
  return schemaDef.parse(json);
}

/* ---------- cursor pagination ---------- */
export function pageParams(req: NextRequest) {
  const limit = Math.min(Math.max(Number(req.nextUrl.searchParams.get("limit") ?? 50), 1), 200);
  const cursor = req.nextUrl.searchParams.get("cursor");
  let after: { at: Date; id: string } | null = null;
  if (cursor) {
    try {
      const [at, id] = Buffer.from(cursor, "base64url").toString().split("|");
      after = { at: new Date(at!), id: id! };
    } catch {
      throw badRequest("Invalid cursor");
    }
  }
  return { limit, after };
}
export function nextCursor<T extends { createdAt: Date; id: string }>(rows: T[], limit: number) {
  if (rows.length <= limit) return { data: rows, next_cursor: null };
  const page = rows.slice(0, limit);
  const last = page[page.length - 1]!;
  return { data: page, next_cursor: Buffer.from(`${last.createdAt.toISOString()}|${last.id}`).toString("base64url") };
}
export function filterParams(req: NextRequest) {
  const out: Record<string, string> = {};
  req.nextUrl.searchParams.forEach((v, k) => {
    const m = k.match(/^filter\[(\w+)\]$/);
    if (m) out[m[1]!] = v;
  });
  return out;
}
