/**
 * GET /api/tasks/status?taskId=X&type=Y&brandId=Z&startedAt=T
 * Checks completion of a background task by querying the appropriate table.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const url = new URL(req.url);
  const type = url.searchParams.get("type");
  const brandId = url.searchParams.get("brandId");
  const startedAt = url.searchParams.get("startedAt");

  if (!type || !brandId) {
    return NextResponse.json({ error: "type and brandId required" }, { status: 400 });
  }

  const since = startedAt ? new Date(startedAt) : new Date(Date.now() - 300000);

  try {
    switch (type) {
      case "technical_audit": {
        const audit = await prisma.technicalAudit.findFirst({
          where: { brandId, createdAt: { gte: since } },
          orderBy: { createdAt: "desc" },
          select: { id: true, pagesScanned: true, errorCount: true, warningCount: true },
        });
        if (audit) return NextResponse.json({
          status: "completed",
          resultUrl: "/technical-audit",
          resultSummary: `Scanned ${audit.pagesScanned} pages: ${audit.errorCount} errors, ${audit.warningCount} warnings`,
        });
        break;
      }

      case "competitor_crawl": {
        const snap = await prisma.competitorSnapshot.findFirst({
          where: { brandId, date: { gte: since } },
          orderBy: { date: "desc" },
          select: { id: true, totalPages: true },
        });
        if (snap) return NextResponse.json({
          status: "completed",
          resultUrl: "/competitors",
          resultSummary: `Crawl complete: ${snap.totalPages ?? 0} pages indexed`,
        });
        break;
      }

      case "keyword_research": {
        const kw = await prisma.trackedKeyword.findFirst({
          where: { brandId, createdAt: { gte: since } },
          orderBy: { createdAt: "desc" },
        });
        if (kw) return NextResponse.json({
          status: "completed",
          resultUrl: "/keyword-research",
          resultSummary: "Keyword analysis complete",
        });
        break;
      }

      case "industry_briefing": {
        const briefing = await prisma.industryBriefing.findFirst({
          where: { brandId, generatedAt: { gte: since } },
          orderBy: { generatedAt: "desc" },
          select: { id: true },
        });
        if (briefing) return NextResponse.json({
          status: "completed",
          resultUrl: "/industry-intel",
          resultSummary: "Industry briefing generated",
        });
        break;
      }

      case "rank_check": {
        const ranking = await prisma.keywordRanking.findFirst({
          where: { trackedKeyword: { brandId }, checkedAt: { gte: since } },
          orderBy: { checkedAt: "desc" },
        });
        if (ranking) return NextResponse.json({
          status: "completed",
          resultUrl: "/rank-tracker",
          resultSummary: "Rank check complete",
        });
        break;
      }

      case "backlink_sync": {
        const snap = await prisma.backlinkSnapshot.findFirst({
          where: { brandId, snapshotDate: { gte: since } },
          orderBy: { snapshotDate: "desc" },
          select: { totalBacklinks: true },
        });
        if (snap) return NextResponse.json({
          status: "completed",
          resultUrl: "/dashboard",
          resultSummary: `Synced ${snap.totalBacklinks} backlinks`,
        });
        break;
      }

      case "dead_page_scan": {
        const record = await prisma.pageStatusChange.findFirst({
          where: { page: { brandId }, detectedAt: { gte: since } },
          orderBy: { detectedAt: "desc" },
        });
        if (record) return NextResponse.json({
          status: "completed",
          resultUrl: "/broken-links",
          resultSummary: "Dead page scan complete",
        });
        break;
      }

      case "gbp_sync": {
        const loc = await prisma.gbpLocation.findFirst({
          where: { brandId, updatedAt: { gte: since } },
          orderBy: { updatedAt: "desc" },
        });
        if (loc) return NextResponse.json({
          status: "completed",
          resultUrl: "/local-geo",
          resultSummary: "GBP sync complete",
        });
        break;
      }

      case "report_generation": {
        // Report generation is typically fast and completes inline
        return NextResponse.json({
          status: "completed",
          resultUrl: "/report-studio",
          resultSummary: "Report generated",
        });
      }
    }

    // If no completed record found, still running
    return NextResponse.json({ status: "running" });
  } catch {
    return NextResponse.json({ status: "running" });
  }
}
