import { db } from "@/db";
import { bankAccounts, emailNotices } from "@/db/schema";
import { getEmailTransport } from "@/lib/email-config";
import { eq } from "drizzle-orm";

export async function sendCustomerNotice(accountId:number,subject:string,body:string,noticeType="account_notice"){const [account]=await db.select({email:bankAccounts.email}).from(bankAccounts).where(eq(bankAccounts.id,accountId)).limit(1);if(!account)return false;let status="filed";const mailer=await getEmailTransport();if(mailer){try{await mailer.transport.sendMail({from:mailer.config.from,to:account.email,subject,text:body});status="sent"}catch(error){console.error("Customer email failed",error);status="failed"}}await db.insert(emailNotices).values({accountId,recipient:account.email,noticeType,subject,body,deliveryStatus:status});return status==="sent"}
export async function sendAdminNotice(subject:string,body:string,noticeType="admin_alert"){const mailer=await getEmailTransport();const recipient=mailer?.config.adminEmail??process.env.ADMIN_EMAIL??"Internal operations portal";let status="filed";if(mailer&&mailer.config.adminEmail){try{await mailer.transport.sendMail({from:mailer.config.from,to:mailer.config.adminEmail,subject,text:body});status="sent"}catch(error){console.error("Admin email failed",error);status="failed"}}await db.insert(emailNotices).values({recipient,noticeType,subject,body,deliveryStatus:status});}

export async function sendEmailVerification(accountId: number, verificationToken: string, baseUrl = "") {
  const [account] = await db.select({ email: bankAccounts.email, firstName: bankAccounts.firstName }).from(bankAccounts).where(eq(bankAccounts.id, accountId)).limit(1);
  if (!account) return false;
  const link = `${baseUrl || ""}/verify-email?token=${verificationToken}`;
  const subject = "Please verify your email address - TRUST WORLD BANK";
  const body = `Hello ${account.firstName},\n\nThank you for banking with TRUST WORLD BANK.\n\nPlease verify your email address to ensure you receive account security alerts and transaction updates.\n\nVerification Token: ${verificationToken}\n\nClick the link below or enter this token on our verification page:\n${link}\n\nIf you did not create or update an account with TRUST WORLD BANK, please contact our security team immediately.`;
  return sendCustomerNotice(accountId, subject, body, "email_verification");
}

export async function sendPasswordResetOtpEmail(accountId: number, email: string, otpCode: string) {
  const subject = "Your Password Reset OTP - TRUST WORLD BANK";
  const body = `Security Notice: Password Recovery Request\n\nYour one-time password recovery code (OTP) is:\n\n${otpCode}\n\nThis OTP code will expire in 10 minutes.\n\nDo not share this OTP code with anyone. TRUST WORLD BANK staff will never ask for your recovery code.\n\nIf you did not request a password reset, please secure your account immediately.`;
  return sendCustomerNotice(accountId, subject, body, "password_reset_otp");
}
