import { cache } from "react";
import { db } from "@/lib/db";

export const getPublicTenant = cache(async (key: string) => {
  const normalized = decodeURIComponent(key).toLowerCase();
  return db.tenant.findFirst({
    where: { status: { in: ["TRIAL", "ACTIVE"] }, deletedAt: null, OR: [{ slug: normalized }, { domains: { some: { hostname: normalized, status: "VERIFIED" } } }] },
    include: { theme: true, domains: { where: { primary: true, status: "VERIFIED" }, take: 1 } },
  });
});

export function tenantUrl(tenant: { slug: string; domains: { hostname: string }[] }) {
  const host = tenant.domains[0]?.hostname ?? `${tenant.slug}.${process.env.ROOT_DOMAIN ?? "localhost:3000"}`;
  const protocol = host.includes("localhost") ? "http" : "https";
  return `${protocol}://${host}`;
}
