/**
 * Brand Data Quality Verification
 * ════════════════════════════════
 * Runs a structured check against a brand's data sources and returns
 * a verification score + list of issues. Used for:
 *   - Onboarding gate (new brands must pass before "ready" status)
 *   - Data Confidence panel scoring
 *   - Admin observability dashboard
 */

import { prisma } from "@/lib/prisma";
import { getDedupQuality } from "./run-dedup";

export interface VerificationIssue {
  severity: "error" | "warning";
  title: string;
  detail: string;
  remediation: string;
}

export interface VerificationResult {
  verified: boolean;
  score: number; // 0-100
  issues: VerificationIssue[];
  checks: {
    siteTagActive: boolean;
    ga4Synced: boolean;
    gscSynced: boolean;
    dedupQuality: number;
    conversionsCaptured: boolean;
  };
}

export async function verifyBrandDataQuality(brandId: string): Promise<VerificationResult> {
  const issues: VerificationIssue[] = [];
  const checks = {
    siteTagActive: false,
    ga4Synced: false,
    gscSynced: false,
    dedupQuality: 0,
    conversionsCaptured: false,
  };

  const d24h = new Date(Date.now() - 24 * 86_400_000);
  const d48h = new Date(Date.now() - 48 * 86_400_000);
  const d7d = new Date(Date.now() - 7 * 86_400_000);

  // 1. Site Tag active (last event within 24h)
  const site = await prisma.trackedSite.findUnique({
    where: { brandId },
    select: { lastEventAt: true },
  }).catch(() => null);

  if (site?.lastEventAt && site.lastEventAt >= d24h) {
    checks.siteTagActive = true;
  } else {
    issues.push({
      severity: "error",
      title: "Site Tag inactive",
      detail: site?.lastEventAt ? `Last event: ${site.lastEventAt.toISOString()}` : "No events ever received",
      remediation: "Verify the Site Tag snippet is installed on all pages and loading correctly.",
    });
  }

  // 2. GA4 synced within 48h
  const ga4 = await prisma.brandIntegration.findFirst({
    where: { brandId, integrationId: "ga4", connected: true },
    select: { lastSynced: true },
  }).catch(() => null);

  if (ga4?.lastSynced && ga4.lastSynced >= d48h) {
    checks.ga4Synced = true;
  } else {
    issues.push({
      severity: ga4 ? "error" : "warning",
      title: "GA4 sync stale",
      detail: ga4?.lastSynced ? `Last synced: ${ga4.lastSynced.toISOString()}` : "GA4 not connected",
      remediation: ga4 ? "Check integration-sync cron logs for errors. May need token refresh." : "Connect GA4 under Integrations.",
    });
  }

  // 3. GSC synced within 7d
  const gsc = await prisma.brandIntegration.findFirst({
    where: { brandId, integrationId: "gsc", connected: true },
    select: { lastSynced: true },
  }).catch(() => null);

  if (gsc?.lastSynced && gsc.lastSynced >= d7d) {
    checks.gscSynced = true;
  } else {
    issues.push({
      severity: gsc ? "error" : "warning",
      title: "GSC sync stale",
      detail: gsc?.lastSynced ? `Last synced: ${gsc.lastSynced.toISOString()}` : "GSC not connected",
      remediation: gsc ? "GSC token may be expired. Re-authenticate under Integrations." : "Connect GSC under Integrations.",
    });
  }

  // 4. Dedup quality >= 90%
  const dedup = await getDedupQuality(brandId, 14);
  checks.dedupQuality = dedup.quality;
  if (dedup.quality < 90) {
    issues.push({
      severity: dedup.quality < 70 ? "error" : "warning",
      title: `Dedup quality: ${dedup.quality}%`,
      detail: `${dedup.duplicates} duplicate conversions out of ${dedup.total} total in last 14 days.`,
      remediation: "The hourly dedup cron will automatically collapse duplicates. Force-run via admin tools if urgent.",
    });
  }

  // 5. At least one conversion in last 7 days
  // intentionally unfiltered: verification helper; scans all rows
  const convCount = await prisma.siteConversion.count({
    where: { brandId, timestamp: { gte: d7d }, isDuplicateOf: null },
  }).catch(() => 0);
  checks.conversionsCaptured = convCount > 0;
  if (convCount === 0) {
    issues.push({
      severity: "warning",
      title: "No recent conversions",
      detail: "Zero conversions captured in the last 7 days.",
      remediation: "Verify form/phone/booking detection is working. Check the Site Tag Events Firing panel.",
    });
  }

  // Score: 20 points per passed check
  const passedChecks = [
    checks.siteTagActive,
    checks.ga4Synced,
    checks.gscSynced,
    checks.dedupQuality >= 90,
    checks.conversionsCaptured,
  ].filter(Boolean).length;
  const score = passedChecks * 20;
  const verified = issues.filter((i) => i.severity === "error").length === 0;

  // Persist verification result
  await prisma.brand.update({
    where: { id: brandId },
    data: {
      verifiedAt: verified ? new Date() : null,
      lastVerificationScore: score,
      lastVerificationIssues: JSON.parse(JSON.stringify(issues)),
    },
  }).catch(() => null);

  return { verified, score, issues, checks };
}
