import "dotenv/config";
import { eq } from "drizzle-orm";
import { hash } from "bcryptjs";
import { getDb } from "../src/core/db/client";
import {
  architectProfiles,
  domains,
  plans,
  projects,
  subscriptions,
  tenantUsers,
  tenants,
  users,
} from "../src/core/db/schema";
import { permissionsForRole } from "../src/core/authorization/authorize";

/**
 * Seeds platform plans + first pilot tenant: Mukhsin Architecture.
 * Mukhsin is a TENANT — not the platform owner.
 */
async function seed() {
  const db = getDb();

  const planDefs = [
    {
      code: "starter",
      name: "Starter",
      description: "Profile, portfolio, ARCHI subdomain, basic analytics",
      entitlements: {
        customDomain: false,
        journal: false,
        teamSeats: 1,
        projects: 10,
      },
    },
    {
      code: "professional",
      name: "Professional",
      description: "Custom domain, SEO, journal, advanced analytics",
      entitlements: {
        customDomain: true,
        journal: true,
        teamSeats: 3,
        projects: 100,
      },
    },
    {
      code: "studio",
      name: "Studio",
      description: "Team, leads, advanced branding, premium features",
      entitlements: {
        customDomain: true,
        journal: true,
        teamSeats: 25,
        projects: 1000,
        leadManagement: true,
      },
    },
  ] as const;

  for (const plan of planDefs) {
    const existing = await db.query.plans.findFirst({
      where: eq(plans.code, plan.code),
    });
    if (!existing) {
      await db.insert(plans).values(plan);
    }
  }

  const ownerEmail = "owner@archi.local";
  let [owner] = await db
    .select()
    .from(users)
    .where(eq(users.email, ownerEmail))
    .limit(1);

  if (!owner) {
    const passwordHash = await hash("ChangeMe-SuperAdmin-2026!", 12);
    [owner] = await db
      .insert(users)
      .values({
        name: "Platform Owner",
        email: ownerEmail,
        passwordHash,
        status: "active",
        platformRole: "super_admin",
        emailVerifiedAt: new Date(),
        mfaEnabled: false,
      })
      .returning();
  }

  const mukhsinEmail = "hello@mukhsin.local";
  let [mukhsinUser] = await db
    .select()
    .from(users)
    .where(eq(users.email, mukhsinEmail))
    .limit(1);

  if (!mukhsinUser) {
    const passwordHash = await hash("ChangeMe-Mukhsin-2026!", 12);
    [mukhsinUser] = await db
      .insert(users)
      .values({
        name: "Mukhsin",
        email: mukhsinEmail,
        passwordHash,
        status: "active",
        platformRole: "none",
        emailVerifiedAt: new Date(),
      })
      .returning();
  }

  let [mukhsinTenant] = await db
    .select()
    .from(tenants)
    .where(eq(tenants.slug, "mukhsin"))
    .limit(1);

  if (!mukhsinTenant) {
    [mukhsinTenant] = await db
      .insert(tenants)
      .values({
        studioName: "Mukhsin Architecture",
        slug: "mukhsin",
        status: "active",
        description: "Pilot tenant studio on ARCHI Platform",
      })
      .returning();

    await db.insert(tenantUsers).values({
      tenantId: mukhsinTenant.id,
      userId: mukhsinUser!.id,
      role: "owner",
      permissions: permissionsForRole("owner"),
      status: "active",
    });

    await db.insert(architectProfiles).values({
      tenantId: mukhsinTenant.id,
      tagline: "Spaces with clarity and permanence",
      about: "Mukhsin Architecture is the first pilot tenant on ARCHI.",
      location: "Dar es Salaam",
      seoTitle: "Mukhsin Architecture",
      seoDescription: "Architecture studio portfolio on ARCHI",
    });

    await db.insert(domains).values({
      tenantId: mukhsinTenant.id,
      domain: "mukhsin.archi.com",
      normalizedDomain: "mukhsin.archi.com",
      type: "subdomain",
      verificationStatus: "verified",
      sslStatus: "active",
      isPrimary: true,
      verifiedAt: new Date(),
    });

    const starter = await db.query.plans.findFirst({
      where: eq(plans.code, "starter"),
    });
    if (starter) {
      await db.insert(subscriptions).values({
        tenantId: mukhsinTenant.id,
        planId: starter.id,
        status: "active",
        currentPeriodStart: new Date(),
        currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
      });
    }

    await db.insert(projects).values({
      tenantId: mukhsinTenant.id,
      title: "Courtyard Residence",
      slug: "courtyard-residence",
      description:
        "A compact urban residence organized around a quiet courtyard.",
      location: "Dar es Salaam",
      year: 2024,
      status: "published",
      publishedAt: new Date(),
    });
  }

  // Isolation counterpart tenant for testing
  let [jumaTenant] = await db
    .select()
    .from(tenants)
    .where(eq(tenants.slug, "juma"))
    .limit(1);

  if (!jumaTenant) {
    [jumaTenant] = await db
      .insert(tenants)
      .values({
        studioName: "Juma Studio",
        slug: "juma",
        status: "active",
      })
      .returning();

    await db.insert(projects).values({
      tenantId: jumaTenant.id,
      title: "Juma Private Project",
      slug: "juma-private-project",
      description: "Must never appear on mukhsin.archi.com",
      status: "published",
      publishedAt: new Date(),
    });
  }

  console.log("Seed complete.");
  console.log("Platform owner:", ownerEmail);
  console.log("Pilot tenant: mukhsin.archi.com / mukhsin.localhost:3000");
  console.log("Isolation tenant: juma.archi.com");
  process.exit(0);
}

seed().catch((error) => {
  console.error(error);
  process.exit(1);
});
