import { asc } from 'drizzle-orm';

import { db } from '@/lib/db';
import { ports } from '@/lib/db/schema/ports';
import { getPortBrandingConfig } from '@/lib/services/port-config';

interface AuthShellBranding {
  logoUrl: string | null;
  backgroundUrl: string | null;
  appName: string | null;
}

/**
 * Pre-port-context surfaces (login, forgot-password, set-password,
 * the better-auth password-reset email) need branding before the user
 * has picked a port. Resolve against the first active port in the
 * system - for a single-tenant deploy that's the right port; for a
 * multi-tenant deploy the operator should host each tenant on its own
 * subdomain so the wrong-tenant logo doesn't surface here.
 *
 * Returns null only if the system has no ports at all (fresh install
 * pre-seed); callers should fall back to neutral defaults in that case.
 */
export async function resolveAuthShellBranding(): Promise<AuthShellBranding | null> {
  try {
    const [port] = await db
      .select({ id: ports.id })
      .from(ports)
      .orderBy(asc(ports.createdAt))
      .limit(1);
    if (!port) return null;

    const cfg = await getPortBrandingConfig(port.id);
    return {
      logoUrl: cfg.logoUrl,
      backgroundUrl: cfg.emailBackgroundUrl,
      appName: cfg.appName,
    };
  } catch {
    return null;
  }
}
