import { prisma } from "@/lib/prisma";
import { detectSnippet } from "./snippet-detector";

const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours

export type SnippetStatus = {
  detected: boolean;
  installationMethod: "direct" | "gtm" | "none" | null;
  detectedAt: Date | null;
  checkedAt: Date | null;
  fromCache: boolean;
};

export async function getOrCheckSnippetStatus(brandId: string, force = false): Promise<SnippetStatus> {
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    select: {
      id: true,
      domain: true,
      snippetDetectedAt: true,
      snippetInstallationMethod: true,
      snippetCheckedAt: true,
    },
  });
  if (!brand) throw new Error(`Brand ${brandId} not found`);
  if (!brand.domain) throw new Error(`Brand ${brandId} has no domain configured`);

  const now = Date.now();
  const lastChecked = brand.snippetCheckedAt?.getTime() ?? 0;

  // Return cached if fresh and not forced
  if (!force && lastChecked && now - lastChecked < CACHE_TTL_MS) {
    return {
      detected: brand.snippetDetectedAt != null,
      installationMethod: (brand.snippetInstallationMethod ?? null) as SnippetStatus["installationMethod"],
      detectedAt: brand.snippetDetectedAt,
      checkedAt: brand.snippetCheckedAt,
      fromCache: true,
    };
  }

  // Fresh check
  const result = await detectSnippet(brand.domain);
  const detected = result.installationMethod === "direct" || result.installationMethod === "gtm";

  const updated = await prisma.brand.update({
    where: { id: brandId },
    data: {
      snippetCheckedAt: new Date(),
      snippetDetectedAt: detected ? new Date() : null,
      snippetInstallationMethod: result.installationMethod,
    },
    select: {
      snippetDetectedAt: true,
      snippetInstallationMethod: true,
      snippetCheckedAt: true,
    },
  });

  return {
    detected,
    installationMethod: (updated.snippetInstallationMethod ?? null) as SnippetStatus["installationMethod"],
    detectedAt: updated.snippetDetectedAt,
    checkedAt: updated.snippetCheckedAt,
    fromCache: false,
  };
}
