import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { getDb } from "@/core/db/client";
import { domains } from "@/core/db/schema";
import type { TenantContext } from "@/core/tenant/types";

function normalizeDomain(domain: string) {
  return domain.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
}

export async function listTenantDomains(ctx: TenantContext) {
  const db = getDb();
  return db
    .select()
    .from(domains)
    .where(eq(domains.tenantId, ctx.tenantId))
    .orderBy(domains.createdAt);
}

export async function addCustomDomain(ctx: TenantContext, rawDomain: string) {
  const db = getDb();
  const normalized = normalizeDomain(rawDomain);

  const [row] = await db
    .insert(domains)
    .values({
      tenantId: ctx.tenantId,
      domain: normalized,
      normalizedDomain: normalized,
      type: "custom",
      verificationStatus: "pending",
      verificationToken: randomUUID(),
      sslStatus: "pending",
      isPrimary: false,
    })
    .returning();

  return row;
}

export async function deleteCustomDomain(ctx: TenantContext, domainId: string) {
  const db = getDb();
  const [existing] = await db
    .select()
    .from(domains)
    .where(
      and(eq(domains.id, domainId), eq(domains.tenantId, ctx.tenantId)),
    )
    .limit(1);

  if (!existing) return null;
  if (existing.type !== "custom") {
    throw new Error("Only custom domains can be removed");
  }

  const [deleted] = await db
    .delete(domains)
    .where(
      and(eq(domains.id, domainId), eq(domains.tenantId, ctx.tenantId)),
    )
    .returning();

  return deleted ?? null;
}

export async function getDomainForTenant(ctx: TenantContext, domainId: string) {
  const db = getDb();
  const [row] = await db
    .select()
    .from(domains)
    .where(
      and(eq(domains.id, domainId), eq(domains.tenantId, ctx.tenantId)),
    )
    .limit(1);
  return row ?? null;
}
