import { getEmailTransport } from "@/lib/email-config";

type AccountNotice = {
  email: string;
  fullName: string;
  userId: string;
  accountNumber: string;
  accountType: string;
  currency: string;
  status: string;
  minimumOpeningDeposit: string;
};

type FiledNotice = { recipient: string; noticeType: string; subject: string; body: string; deliveryStatus: string };

export async function sendAccountNotices(notice: AccountNotice): Promise<{ sent: boolean; notices: FiledNotice[] }> {
  const customerSubject = "Your TRUST WORLD BANK enrollment confirmation";
  const customerBody = `Hello ${notice.fullName},\n\nWe received your TRUST WORLD BANK ${notice.accountType} enrollment.\n\nAccount number: ${notice.accountNumber}\nUser ID: ${notice.userId}\nCurrency: ${notice.currency}\nStatus: Pending identity verification\n\nFor your security, your password and security PIN are never sent by email and cannot be viewed by bank staff. Use the credentials you created to sign in. Do not share them with anyone.\n\nThis enrollment remains subject to identity and compliance review.\n\nNext step: contact TRUST WORLD BANK through an official support channel for approved instructions to make the minimum opening deposit of ${notice.minimumOpeningDeposit} ${notice.currency}. Your account cannot be activated until the bank receives and posts the deposit.`;
  const mailer = await getEmailTransport();
  const adminEmail = mailer?.config.adminEmail ?? process.env.ADMIN_EMAIL ?? "Internal operations portal";
  const adminSubject = `New account enrollment: ${notice.accountType}`;
  const adminBody = `A new account enrollment is ready for review in the protected admin portal.\n\nCustomer: ${notice.fullName}\nAccount: ${notice.accountNumber}\nUser ID: ${notice.userId}\nType: ${notice.accountType}\nCurrency: ${notice.currency}\nStatus: ${notice.status}\n\nSensitive credentials and full identity numbers are intentionally excluded from email.`;
  const notices: FiledNotice[] = [
    { recipient: notice.email, noticeType: "welcome", subject: customerSubject, body: customerBody, deliveryStatus: "filed" },
    { recipient: adminEmail, noticeType: "admin_alert", subject: adminSubject, body: adminBody, deliveryStatus: "filed" },
  ];
  if (!mailer) {
    console.info("SMTP is not configured; notices filed but not delivered.");
    return { sent: false, notices };
  }
  const from = mailer.config.from;
  await mailer.transport.sendMail({ from, to: notice.email, subject: customerSubject, text: customerBody });
  notices[0].deliveryStatus = "sent";
  if (mailer.config.adminEmail) {
    await mailer.transport.sendMail({ from, to: mailer.config.adminEmail, subject: adminSubject, text: adminBody });
    notices[1].deliveryStatus = "sent";
  }
  return { sent: true, notices };
}
