import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function main() {
  console.log("Seeding database...");

  // Create test user (Clerk will sync real users, this is for dev)
  const user = await prisma.user.upsert({
    where: { email: "demo@meseo.com" },
    update: {},
    create: {
      id: "user_demo",
      name: "Dylan Mazzei",
      email: "demo@meseo.com",
    },
  });
  console.log("Created user:", user.email);

  // Create organization
  const org = await prisma.organization.upsert({
    where: { slug: "mazzei-agency" },
    update: {},
    create: {
      name: "Mazzei Agency",
      slug: "mazzei-agency",
      plan: "pro",
    },
  });
  console.log("Created org:", org.name);

  // Add user as owner
  await prisma.orgMembership.upsert({
    where: { userId_orgId: { userId: user.id, orgId: org.id } },
    update: {},
    create: { userId: user.id, orgId: org.id, role: "owner" },
  });
  console.log("Added user as org owner");

  // Create brands
  const brands = [
    {
      id: "acme-corp",
      name: "Acme Corp",
      domain: "acme.com",
      industry: "Technology",
      initials: "AC",
      color: "bg-brand-500",
      healthScore: 74,
      websites: [{ url: "https://acme.com", isPrimary: true, pageCount: 1248 }],
      dashboard: { seoScore: 74, aiVisibility: 12, crawlHealth: 94, monthlyTraffic: 8420, revenue: 24800, revenueChange: 14, alertCount: 7 },
      profile: {
        companyName: "Acme Corp",
        businessType: "SaaS",
        services: ["SEO Auditing", "Technical SEO", "Content Strategy", "AI Visibility Tracking"],
        locations: ["New York, NY", "San Francisco, CA"],
        brandColors: ["#3b5cf0", "#1e293b", "#f8fafc"],
        targetAudience: "Mid-market B2B SaaS companies",
        description: "Project management and productivity platform for modern teams.",
      },
    },
    {
      id: "beacon-health",
      name: "Beacon Health",
      domain: "beaconhq.com",
      industry: "Healthcare",
      initials: "BH",
      color: "bg-emerald-500",
      healthScore: 82,
      websites: [{ url: "https://beaconhq.com", isPrimary: true, pageCount: 890 }],
      dashboard: { seoScore: 82, aiVisibility: 18, crawlHealth: 91, monthlyTraffic: 12300, revenue: 38200, revenueChange: 8, alertCount: 3 },
      profile: {
        companyName: "Beacon Health",
        businessType: "Healthcare",
        services: ["Primary Care", "Telehealth", "Wellness Programs", "Health Coaching"],
        locations: ["Boston, MA", "Providence, RI"],
        brandColors: ["#10b981", "#064e3b", "#ecfdf5"],
        targetAudience: "Health-conscious adults aged 25-55",
        description: "Modern healthcare platform connecting patients with providers.",
      },
    },
    {
      id: "nova-digital",
      name: "Nova Digital",
      domain: "novadigital.io",
      industry: "Technology",
      initials: "ND",
      color: "bg-violet-500",
      healthScore: 61,
      websites: [{ url: "https://novadigital.io", isPrimary: true, pageCount: 412 }],
      dashboard: { seoScore: 61, aiVisibility: 5, crawlHealth: 78, monthlyTraffic: 3200, revenue: 8400, revenueChange: -3, alertCount: 12 },
      profile: {
        companyName: "Nova Digital",
        businessType: "Agency",
        services: ["Web Design", "SEO", "PPC", "Social Media Marketing"],
        locations: ["Austin, TX"],
        brandColors: ["#8b5cf6", "#4c1d95", "#f5f3ff"],
        targetAudience: "Small businesses looking for digital marketing services",
        description: "Full-service digital marketing agency for growing businesses.",
      },
    },
  ];

  for (const b of brands) {
    await prisma.brand.deleteMany({ where: { id: b.id } });

    const brand = await prisma.brand.create({
      data: {
        id: b.id,
        name: b.name,
        domain: b.domain,
        industry: b.industry,
        initials: b.initials,
        color: b.color,
        healthScore: b.healthScore,
        orgId: org.id,
        websites: {
          create: b.websites.map((w) => ({
            url: w.url,
            isPrimary: w.isPrimary,
            pageCount: w.pageCount,
          })),
        },
        dashboardData: {
          create: b.dashboard,
        },
        profile: {
          create: b.profile,
        },
      },
    });

    // Add default integrations per brand
    const defaultIntegrations: Record<string, string[]> = {
      "acme-corp": ["gsc", "ga4", "chatgpt", "claude", "callrail", "stripe", "pagespeed", "lighthouse", "sheets"],
      "beacon-health": ["gsc", "ga4", "gbp", "chatgpt", "claude", "callrail", "pagespeed", "lighthouse"],
      "nova-digital": ["gsc", "ga4", "chatgpt"],
    };

    const brandIntegrations = defaultIntegrations[b.id] || [];
    for (const integrationId of brandIntegrations) {
      await prisma.brandIntegration.upsert({
        where: { brandId_integrationId: { brandId: brand.id, integrationId } },
        update: {},
        create: {
          brandId: brand.id,
          integrationId,
          connected: true,
          lastSynced: new Date(Date.now() - Math.random() * 86400000),
        },
      });
    }

    console.log("Created brand:", brand.name, `with ${brandIntegrations.length} integrations`);
  }

  console.log("Seeding complete!");
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
