import { prisma } from "@/lib/prisma";

export type IssueSeverity = "critical" | "high" | "medium" | "low";
export type IssueCategory = "metadata" | "headings" | "crawl" | "links" | "redirects" | "indexability";

/**
 * Get the latest technical audit for a brand.
 * Optional filters: severity, category, status
 * Optional sort: "severity" (default) | "affected" | "category"
 */
export async function getLatestAudit(
  brandId: string,
  filters?: { severity?: IssueSeverity; category?: IssueCategory; status?: string },
  sort?: string
) {
  const audit = await prisma.technicalAudit.findFirst({
    where: { brandId, status: "completed" },
    orderBy: { createdAt: "desc" },
    include: {
      issues: {
        where: {
          ...(filters?.severity ? { severity: filters.severity } : {}),
          ...(filters?.category ? { category: filters.category } : {}),
          ...(filters?.status ? { status: filters.status } : {}),
        },
        orderBy: sort === "affected" ? { affected: "desc" }
               : sort === "category" ? { category: "asc" }
               : [{ severity: "asc" }, { affected: "desc" }],
      },
    },
  });

  if (!audit) return null;

  // Group issues by category
  const byCategory: Record<string, typeof audit.issues> = {};
  for (const issue of audit.issues) {
    if (!byCategory[issue.category]) byCategory[issue.category] = [];
    byCategory[issue.category].push(issue);
  }

  // Group by severity
  const bySeverity: Record<string, number> = { critical: 0, high: 0, medium: 0, low: 0 };
  for (const issue of audit.issues) {
    bySeverity[issue.severity] = (bySeverity[issue.severity] || 0) + 1;
  }

  return {
    ...audit,
    byCategory,
    bySeverity,
  };
}

/**
 * Create a new audit run with issues.
 */
export async function createAudit(brandId: string, data: {
  crawlHealth: number;
  pagesScanned: number;
  duration: number;
  issues: Array<{
    category: IssueCategory;
    severity: IssueSeverity;
    title: string;
    detail?: string;
    pageUrl?: string;
    affected?: number;
  }>;
}) {
  const errorCount = data.issues.filter((i) => i.severity === "critical" || i.severity === "high").length;
  const warningCount = data.issues.filter((i) => i.severity === "medium").length;
  const noticeCount = data.issues.filter((i) => i.severity === "low").length;

  return prisma.technicalAudit.create({
    data: {
      brandId,
      crawlHealth: data.crawlHealth,
      pagesScanned: data.pagesScanned,
      duration: data.duration,
      errorCount,
      warningCount,
      noticeCount,
      passedCount: Math.max(0, data.pagesScanned - errorCount - warningCount - noticeCount),
      issues: {
        create: data.issues.map((i) => ({
          category: i.category,
          severity: i.severity,
          title: i.title,
          detail: i.detail,
          pageUrl: i.pageUrl,
          affected: i.affected ?? 1,
        })),
      },
    },
    include: { issues: true },
  });
}
