import { NextRequest, NextResponse } from "next/server";
import { db, isDatabaseAvailable } from "@/lib/db";
import { ensureDatabaseInitialized } from "@/lib/db/init";
import { getAdminUser } from "@/lib/auth/admin";
import { clientIp } from "@/lib/auth/rateLimit";
import {
  logSecurityEventAsync,
  SecurityEventType,
} from "@/lib/auth/securityEvents";
import { count, desc, eq, gte, isNotNull, sql } from "drizzle-orm";
import { receipts, users } from "@/lib/schema/db";

export const runtime = "nodejs";

const THIRTY_DAYS_AGO = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

const CATEGORY_COLORS = [
  "#3b82f6",
  "#10b981",
  "#f59e0b",
  "#ef4444",
  "#8b5cf6",
  "#06b6d4",
  "#ec4899",
  "#84cc16",
  "#f97316",
  "#64748b",
];

export async function GET(req: NextRequest) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

  logSecurityEventAsync({
    type: SecurityEventType.ADMIN_ACTION,
    userId: admin.id,
    email: admin.email,
    ip: clientIp(req),
    userAgent: req.headers.get("user-agent"),
    metadata: { route: "/api/admin/receipts", method: "GET" },
  });

  if (!(await isDatabaseAvailable())) {
    return NextResponse.json({ error: 'Database unavailable' }, { status: 503 });
  }
  await ensureDatabaseInitialized();

  try {
    const statsRow = await db
      .select({
        totalReceipts: count(),
        mathValidCount: sql<number>`count(*) FILTER (WHERE ${receipts.isMathValid} = true)`,
        needsReview: sql<number>`count(*) FILTER (WHERE ${receipts.needsReview} = true)`,
      })
      .from(receipts);

    const stats = statsRow[0];
    const totalReceipts = Number(stats?.totalReceipts ?? 0);
    const mathValidRate =
      totalReceipts > 0 ? (Number(stats?.mathValidCount ?? 0) / totalReceipts) * 100 : 0;

    const categoryRows = await db
      .select({ label: receipts.category, count: count() })
      .from(receipts)
      .where(isNotNull(receipts.category))
      .groupBy(receipts.category)
      .orderBy(desc(count()));

    const topScannerRows = await db
      .select({
        email: users.email,
        name: users.name,
        count: users.scanCount,
      })
      .from(users)
      .where(eq(users.isGuest, false))
      .orderBy(desc(users.scanCount))
      .limit(10);

    const dailyScanRows = await db
      .select({
        date: sql<string>`DATE(${receipts.createdAt})`,
        count: count(),
      })
      .from(receipts)
      .where(gte(receipts.createdAt, THIRTY_DAYS_AGO))
      .groupBy(sql`DATE(${receipts.createdAt})`)
      .orderBy(sql`DATE(${receipts.createdAt}) ASC`);

    return NextResponse.json({
      totalReceipts,
      mathValidRate,
      needsReview: Number(stats?.needsReview ?? 0),
      categories: categoryRows.map((r, i) => ({
        label: r.label ?? "Sonstiges",
        count: Number(r.count),
        color: CATEGORY_COLORS[i % CATEGORY_COLORS.length],
      })),
      topScanners: topScannerRows.map((r, i) => ({
        rank: i + 1,
        email: r.email ?? "",
        name: r.name,
        count: Number(r.count ?? 0),
      })),
      dailyScans: dailyScanRows.map((r) => ({
        date: String(r.date),
        count: Number(r.count),
      })),
    });
  } catch (error) {
    console.error("Admin receipts error:", error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}