import { db, prismaUnscoped } from './prisma';

/**
 * What an email carries about the sender: the hostel's registered name, its
 * accent colour, and how to reach the office. All of it comes from the
 * billing identity the owner already fills in for invoices, so a mail and a
 * receipt look like the same business.
 */
export interface EmailBrand {
  firm: string;
  accent?: string | null;
  address?: string | null;
  phone?: string | null;
  email?: string | null;
}

type Row = { billingFirmName: string | null; billingAccentColor: string | null; billingAddress: string | null; billingPhone: string | null; billingEmail: string | null } | null;

export const BRAND_SELECT = { billingFirmName: true, billingAccentColor: true, billingAddress: true, billingPhone: true, billingEmail: true } as const;

export function brandFromSettings(settings: Row, fallbackFirm?: string | null): EmailBrand {
  return {
    firm: settings?.billingFirmName?.trim() || fallbackFirm?.trim() || 'HostelCare',
    accent: settings?.billingAccentColor ?? null,
    address: settings?.billingAddress ?? null,
    phone: settings?.billingPhone ?? null,
    email: settings?.billingEmail ?? null,
  };
}

/** Inside a request: the signed-in hostel's brand. */
export async function currentBrand(fallbackFirm?: string | null): Promise<EmailBrand> {
  const settings = await db.tenantSettings.findFirst({ select: BRAND_SELECT });
  return brandFromSettings(settings, fallbackFirm);
}

/** On a background tick, where there is no request context. */
export async function brandForTenant(tenantId: string, fallbackFirm?: string | null): Promise<EmailBrand> {
  const [settings, tenant] = await Promise.all([
    prismaUnscoped.tenantSettings.findUnique({ where: { tenantId }, select: BRAND_SELECT }),
    fallbackFirm ? null : prismaUnscoped.tenant.findUnique({ where: { id: tenantId }, select: { name: true } }),
  ]);
  return brandFromSettings(settings, fallbackFirm ?? tenant?.name);
}
