/**
 * POST /api/admin/demo-brand/create
 * ──────────────────────────────────
 * Idempotent. Creates a demo brand (isDemo: true) in the specified
 * org so it appears in the brand-switcher dropdown for showcase.
 *
 * Auth: x-admin-secret header must match ADMIN_SECRET env var.
 *
 * Body:
 *   orgId   string  required — org to attach the demo brand to
 *
 * Returns:
 *   { brand, trackedSiteId, alreadyExisted }
 *   trackedSiteId is needed for the seed endpoints (Phase 1).
 */

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

export const dynamic = "force-dynamic";
export const maxDuration = 60;

const DEMO_DOMAIN = "demo.heartwellcardiology.com";
const DEMO_NAME = "Heartwell Cardiology (Demo)";

export async function POST(req: Request) {
  const secret = req.headers.get("x-admin-secret");
  if (!secret || secret !== process.env.ADMIN_SECRET) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await req.json().catch(() => null) as { orgId?: string } | null;
  if (!body?.orgId) {
    return NextResponse.json({ error: "orgId required" }, { status: 400 });
  }

  const org = await prisma.organization.findUnique({ where: { id: body.orgId } });
  if (!org) return NextResponse.json({ error: "Organization not found" }, { status: 404 });

  // Idempotent — return existing demo brand if already created for this org
  const existing = await prisma.brand.findFirst({
    where: { orgId: body.orgId, isDemo: true, domain: DEMO_DOMAIN },
    include: { trackedSite: { select: { id: true } } },
  });

  if (existing) {
    // Ensure the BrandMembership exists for org members (idempotent findFirst+create)
    const orgMembers = await prisma.orgMembership.findMany({
      where: { orgId: body.orgId },
      select: { userId: true },
    });
    for (const m of orgMembers) {
      const existingMembership = await prisma.brandMembership.findFirst({
        where: { brandId: existing.id, userId: m.userId },
      });
      if (!existingMembership) {
        await prisma.brandMembership.create({
          data: { brandId: existing.id, userId: m.userId, role: "member" },
        });
      }
    }
    return NextResponse.json({
      alreadyExisted: true,
      brand: { id: existing.id, name: existing.name, domain: existing.domain },
      trackedSiteId: existing.trackedSite?.id ?? null,
    });
  }

  // Create the demo brand
  const brand = await prisma.brand.create({
    data: {
      name: DEMO_NAME,
      domain: DEMO_DOMAIN,
      industry: "Healthcare",
      initials: "HC",
      plan: "professional",
      color: "bg-emerald-500",
      status: "active",
      isDemo: true,
      locations: ["Houston, TX", "Sugar Land, TX"],
      primaryServices: ["Cardiology", "Cardiac Imaging"],
      secondaryServices: ["Electrophysiology", "Heart Failure Management", "Preventive Cardiology"],
      location: "Houston, TX",
      serviceType: "Cardiology",
      orgId: body.orgId,
      profile: {
        create: {
          shortDescription: "Award-winning cardiology practice serving Greater Houston since 1998.",
          industry: "Healthcare",
          brandVoice: "Professional, compassionate, evidence-based",
        },
      },
      websites: {
        create: {
          url: `https://${DEMO_DOMAIN}`,
          isPrimary: true,
        },
      },
    },
  });

  // Create TrackedSite (needed for session/event seeding)
  const siteId = `ms_demo_${brand.id.slice(-8)}`;
  const trackingKey = `tk_demo_${brand.id.slice(-12)}`;
  const trackedSite = await prisma.trackedSite.create({
    data: {
      siteId,
      trackingKey,
      status: "active",
      allowedDomains: [DEMO_DOMAIN],
      orgId: body.orgId,
      brandId: brand.id,
    },
  });

  // Create GBP locations
  await prisma.gbpLocation.createMany({
    data: [
      {
        brandId: brand.id,
        googleLocationId: `demo_gbp_houston_${brand.id.slice(-6)}`,
        locationName: "Heartwell Cardiology – Houston Medical Center",
        address: "6560 Fannin St",
        city: "Houston",
        state: "TX",
        zip: "77030",
        phone: "(713) 555-0192",
        isActive: true,
        avgRating: 4.8,
        totalReviews: 312,
      },
      {
        brandId: brand.id,
        googleLocationId: `demo_gbp_sugarland_${brand.id.slice(-6)}`,
        locationName: "Heartwell Cardiology – Sugar Land",
        address: "77 Sugar Creek Center Blvd",
        city: "Sugar Land",
        state: "TX",
        zip: "77478",
        phone: "(281) 555-0247",
        isActive: true,
        avgRating: 4.7,
        totalReviews: 187,
      },
    ],
  });

  // Create DashboardData (baseline)
  await prisma.dashboardData.create({
    data: {
      brandId: brand.id,
      seoScore: 74,
      aiVisibility: 62,
      crawlHealth: 81,
      monthlyTraffic: 24800,
      revenue: 0,
      revenueChange: 0,
      alertCount: 3,
    },
  });

  // Grant all org members access to the demo brand
  const orgMembers = await prisma.orgMembership.findMany({
    where: { orgId: body.orgId },
    select: { userId: true, role: true },
  });
  await prisma.brandMembership.createMany({
    data: orgMembers.map((m) => ({
      brandId: brand.id,
      userId: m.userId,
      role: m.role === "owner" ? "owner" : "member",
    })),
    skipDuplicates: true,
  });

  console.info(`[demo-brand/create] created demo brand ${brand.id} (${DEMO_NAME}) in org ${body.orgId}`);

  return NextResponse.json({
    alreadyExisted: false,
    brand: { id: brand.id, name: brand.name, domain: brand.domain },
    trackedSiteId: trackedSite.id,
  }, { status: 201 });
}
