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

/**
 * Get dead pages for a brand.
 * Optional filters: status, priority
 * Optional sort: "priority" (default) | "discovered" | "sources"
 */
export async function getDeadPages(
  brandId: string,
  filters?: { status?: string; priority?: string },
  sort?: string
) {
  return prisma.deadPage.findMany({
    where: {
      brandId,
      ...(filters?.status ? { status: filters.status } : {}),
      ...(filters?.priority ? { priority: filters.priority } : {}),
    },
    include: { sources: true },
    orderBy: sort === "discovered" ? { discoveredAt: "desc" }
           : sort === "sources" ? { sources: { _count: "desc" } }
           : [{ priority: "asc" }, { discoveredAt: "desc" }],
  });
}

/**
 * Create a dead page record with source links.
 */
export async function createDeadPage(data: {
  brandId: string;
  deadUrl: string;
  priority?: string;
  suggestedFix?: string;
  sources: Array<{ sourceUrl: string; anchorText?: string }>;
}) {
  return prisma.deadPage.create({
    data: {
      brandId: data.brandId,
      deadUrl: data.deadUrl,
      priority: data.priority ?? "medium",
      suggestedFix: data.suggestedFix,
      sources: {
        create: data.sources,
      },
    },
    include: { sources: true },
  });
}

/**
 * Update dead page status (open → fixed, redirected, ignored).
 */
export async function updateDeadPageStatus(deadPageId: string, status: string, suggestedFix?: string) {
  return prisma.deadPage.update({
    where: { id: deadPageId },
    data: { status, ...(suggestedFix ? { suggestedFix } : {}) },
  });
}
