import PaymentLink from '../Features/payment-links/schema/payment-link.schema';
import { sendSms } from './sms.helper';
import { sendTransactionalEmail } from './emailer';
import { getBusinessProfile } from './site-settings.helper';
import {
  buildBookingConfirmationEmailHtml,
  buildBookingConfirmationEmailText,
  buildBookingConfirmationSms,
  buildBookingReference,
} from './notification-messages.helper';

async function resolvePaymentLink(appointment: { paymentLinkId?: string | null }) {
  if (!appointment.paymentLinkId) return null;
  const link = await PaymentLink.findById(appointment.paymentLinkId).lean();
  if (!link) return null;
  return {
    url: link.url,
    amount: link.amount,
    status: link.status,
  };
}

export async function sendBookingNotifications(appointment: {
  _id: unknown;
  fullName: string;
  email?: string;
  phone?: string;
  service: string;
  date: string;
  time: string;
  notes?: string;
  paymentLinkId?: string | null;
  lineItems?: unknown[];
}) {
  const business = await getBusinessProfile();
  const paymentLink = await resolvePaymentLink(appointment);
  const reference = buildBookingReference(appointment._id);
  const context = {
    appointment: appointment as Record<string, unknown>,
    business,
    paymentLink,
    reference,
  };

  const results = { sms: false, email: false };

  const phone = String(appointment.phone || '').trim();
  if (phone) {
    const message = buildBookingConfirmationSms(context);
    results.sms = await sendSms(phone, message);
  }

  const email = String(appointment.email || '').trim().toLowerCase();
  if (email) {
    const subject = `${business.name} — Booking Confirmed (${reference})`;
    results.email = await sendTransactionalEmail({
      to: email,
      subject,
      html: buildBookingConfirmationEmailHtml(context),
      text: buildBookingConfirmationEmailText(context),
    });
  }

  return results;
}
