/** Tenant-level SMTP storage helpers (restaurant override). */
import { db } from '@server/db/drizzle';
import { sql } from 'drizzle-orm';
import { encryptSecret, decryptSecret } from './platform-settings';

export interface RestaurantSmtpConfig {
  host: string;
  port: number;
  user: string;
  pass: string;
  from: string;
  secure?: boolean;
}

export interface RestaurantSmtpView {
  enabled: boolean;
  host: string;
  port: number;
  user: string;
  from: string;
  secure: boolean;
  passSet: boolean;
}

export async function getRestaurantSmtpView(restaurantId: string): Promise<RestaurantSmtpView> {
  const { rows } = await db.execute(sql`
    SELECT smtp_host, smtp_port, smtp_user, smtp_pass_enc, smtp_from, smtp_secure, smtp_enabled
    FROM restaurants WHERE id = ${restaurantId}
  `);
  const row = rows[0] as Record<string, unknown> | undefined;
  return {
    enabled: !!row?.smtp_enabled,
    host: (row?.smtp_host as string) ?? '',
    port: (row?.smtp_port as number) ?? 587,
    user: (row?.smtp_user as string) ?? '',
    from: (row?.smtp_from as string) ?? '',
    secure: !!row?.smtp_secure,
    passSet: !!row?.smtp_pass_enc,
  };
}

export async function getRestaurantSmtp(restaurantId: string): Promise<RestaurantSmtpConfig | null> {
  const { rows } = await db.execute(sql`
    SELECT smtp_host, smtp_port, smtp_user, smtp_pass_enc, smtp_from, smtp_secure, smtp_enabled
    FROM restaurants WHERE id = ${restaurantId}
  `);
  const row = rows[0] as Record<string, unknown> | undefined;
  if (!row) return null;
  if (!row.smtp_enabled) return null;
  const host = row.smtp_host as string | null;
  const user = row.smtp_user as string | null;
  const passEnc = row.smtp_pass_enc as string | null;
  if (!host || !user || !passEnc) return null;
  const pass = decryptSecret(passEnc);
  if (!pass) return null;
  return {
    host,
    port: (row.smtp_port as number | null) ?? 587,
    user,
    pass,
    from: (row.smtp_from as string | null) || user,
    secure: !!row.smtp_secure,
  };
}

export interface SaveRestaurantSmtpInput {
  enabled: boolean;
  host: string;
  port: number;
  user: string;
  pass?: string; // blank means keep existing
  from: string;
  secure?: boolean;
}

export async function setRestaurantSmtp(restaurantId: string, input: SaveRestaurantSmtpInput): Promise<void> {
  const passEnc = input.pass ? encryptSecret(input.pass) : null;
  if (passEnc) {
    await db.execute(sql`
      UPDATE restaurants SET
        smtp_host = ${input.host || null},
        smtp_port = ${input.port || 587},
        smtp_user = ${input.user || null},
        smtp_pass_enc = ${passEnc},
        smtp_from = ${input.from || null},
        smtp_secure = ${!!input.secure},
        smtp_enabled = ${!!input.enabled},
        updated_at = NOW()
      WHERE id = ${restaurantId}
    `);
  } else {
    await db.execute(sql`
      UPDATE restaurants SET
        smtp_host = ${input.host || null},
        smtp_port = ${input.port || 587},
        smtp_user = ${input.user || null},
        smtp_from = ${input.from || null},
        smtp_secure = ${!!input.secure},
        smtp_enabled = ${!!input.enabled},
        updated_at = NOW()
      WHERE id = ${restaurantId}
    `);
  }
}

export async function clearRestaurantSmtp(restaurantId: string): Promise<void> {
  await db.execute(sql`
    UPDATE restaurants SET
      smtp_host = NULL, smtp_port = NULL, smtp_user = NULL,
      smtp_pass_enc = NULL, smtp_from = NULL, smtp_secure = false,
      smtp_enabled = false, updated_at = NOW()
    WHERE id = ${restaurantId}
  `);
}
