import crypto from "crypto";
import { NextRequest, NextResponse } from "next/server";
import { db, isDatabaseAvailable } from "@/lib/db";
import { ensureDatabaseInitialized } from "@/lib/db/init";
import { projects, receipts } from "@/lib/schema/db";
import { eq, and, count, desc } from "drizzle-orm";
import { getCurrentUser } from "@/lib/auth/session";
import { requireCsrf } from "@/lib/auth/csrf";
import { sanitizeText } from "@/lib/ingest/sanitize";
import { isProActive } from "@/lib/billing/access";
import {
  resolveGuestContext,
  applyGuestCookie,
  type GuestContext,
} from "@/lib/auth/guest";

export const runtime = "nodejs";

const PROJECT_NAME_MAX_LENGTH = 120;
const PROJECT_COLORS = ["slate", "blue", "emerald", "amber", "rose", "violet"];

/** Same scoping rule as /api/receipts: signed-in users own their bucket, guests get a per-browser one. */
async function resolveScope(req: NextRequest): Promise<{
  user: Awaited<ReturnType<typeof getCurrentUser>>;
  userId: string;
  guest: GuestContext | null;
}> {
  const user = await getCurrentUser(req);
  if (user) return { user, userId: user.id, guest: null };

  const guest = resolveGuestContext(req);
  return { user: null, userId: guest.bucket, guest };
}

/** Projects are a Pro feature: creating/renaming/deleting/assigning all require an active paid plan. */
function isProUser(user: Awaited<ReturnType<typeof getCurrentUser>>): boolean {
  return isProActive(user);
}

/**
 * GET /api/projects
 * Lists the caller's projects with their receipt counts. Left ungated (unlike
 * the mutating endpoints below) so a user who downgraded from Pro can still
 * see how their existing receipts are organized, just not change it.
 */
export async function GET(req: NextRequest) {
  try {
    const dbAvailable = await isDatabaseAvailable();
    if (!dbAvailable) {
      return NextResponse.json(
        { success: false, projects: [] },
        { status: 503 }
      );
    }

    await ensureDatabaseInitialized();
    const scope = await resolveScope(req);

    const [projectRows, countRows] = await Promise.all([
      db
        .select()
        .from(projects)
        .where(eq(projects.userId, scope.userId))
        .orderBy(desc(projects.createdAt)),
      db
        .select({ projectId: receipts.projectId, receiptCount: count() })
        .from(receipts)
        .where(eq(receipts.userId, scope.userId))
        .groupBy(receipts.projectId),
    ]);

    const countByProject = new Map(
      countRows
        .filter((row) => row.projectId != null)
        .map((row) => [row.projectId as string, row.receiptCount])
    );

    return applyGuestCookie(
      NextResponse.json({
        success: true,
        projects: projectRows.map((p) => ({
          id: p.id,
          name: p.name,
          color: p.color,
          receiptCount: countByProject.get(p.id) ?? 0,
          createdAt: p.createdAt.toISOString(),
          updatedAt: p.updatedAt.toISOString(),
        })),
      }),
      scope.guest
    );
  } catch (error: any) {
    console.error("GET /api/projects error:", error);
    return NextResponse.json({ success: false, projects: [] }, { status: 500 });
  }
}

/**
 * POST /api/projects
 * Creates a new project (folder). Pro-only — guests and free-plan accounts
 * are rejected with 402 so the client can surface the paywall.
 */
export async function POST(req: NextRequest) {
  try {
    const csrfBlocked = requireCsrf(req);
    if (csrfBlocked) return csrfBlocked;

    const dbAvailable = await isDatabaseAvailable();
    if (!dbAvailable) {
      return NextResponse.json({ error: "Database unavailable." }, { status: 503 });
    }

    await ensureDatabaseInitialized();
    const scope = await resolveScope(req);

    if (!isProUser(scope.user)) {
      return NextResponse.json({ error: "pro_required" }, { status: 402 });
    }

    const body = await req.json().catch(() => null);
    const name = sanitizeText(body?.name, PROJECT_NAME_MAX_LENGTH);
    if (!name) {
      return NextResponse.json({ error: "Project name is required." }, { status: 400 });
    }
    const color = PROJECT_COLORS.includes(body?.color) ? body.color : null;

    const id = `proj_${Date.now()}_${crypto.randomBytes(4).toString("hex")}`;

    const [created] = await db
      .insert(projects)
      .values({ id, userId: scope.userId, name, color })
      .returning();

    return applyGuestCookie(
      NextResponse.json({
        success: true,
        project: {
          id: created.id,
          name: created.name,
          color: created.color,
          receiptCount: 0,
          createdAt: created.createdAt.toISOString(),
          updatedAt: created.updatedAt.toISOString(),
        },
      }),
      scope.guest
    );
  } catch (error: any) {
    if (error?.code === "23505") {
      return NextResponse.json(
        { error: "A project with this name already exists." },
        { status: 409 }
      );
    }
    console.error("POST /api/projects error:", error);
    return NextResponse.json({ error: "Failed to create project." }, { status: 500 });
  }
}
