package com.mvrent.carrental.service;

import com.mvrent.carrental.model.Booking;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Composes transactional notifications and hands them to {@link MailDispatcher}
 * for async, fail-safe delivery. Bodies are built by the caller (inside its
 * transaction) so no lazy associations are touched off the request thread.
 */
@Service
@RequiredArgsConstructor
public class NotificationService {

    private final MailDispatcher mailDispatcher;

    @Value("${app.mail.admin:}")
    private String adminEmail;
    @Value("${app.currency.symbol:₹}")
    private String currency;

    public boolean isReady() { return mailDispatcher.isReady(); }

    public String adminEmail() { return adminEmail; }

    /* ---------- Booking events (composed in-tx, sent async) ---------- */

    public void sendBookingConfirmation(Booking b) {
        if (b.getUser() == null || b.getUser().getEmail() == null) return;
        String car = b.getCar() != null ? b.getCar().getMake() + " " + b.getCar().getModel() : "your vehicle";
        String subject = "Booking confirmed — #" + b.getId();
        String body = "Hi " + safeName(b) + ",\n\n"
                + "Your booking #" + b.getId() + " is confirmed.\n\n"
                + "Car: " + car + "\n"
                + "Pickup: " + b.getPickupDate() + " from " + b.getPickupLocation() + "\n"
                + "Return: " + b.getReturnDate() + " at " + b.getDropLocation() + "\n"
                + (b.isWithDriver() ? "Driver: included\n" : "")
                + "Total: " + currency + b.getTotalAmount() + "\n\n"
                + "Thank you for choosing MV Rent.";
        mailDispatcher.send(b.getUser().getEmail(), subject, body);
    }

    public void sendBookingStatusUpdate(Booking b) {
        if (b.getUser() == null || b.getUser().getEmail() == null) return;
        String subject = "Booking #" + b.getId() + " — " + b.getStatus();
        String body = "Hi " + safeName(b) + ",\n\n"
                + "The status of your booking #" + b.getId() + " is now: " + b.getStatus() + ".\n\n"
                + "— MV Rent";
        mailDispatcher.send(b.getUser().getEmail(), subject, body);
    }

    /** Synchronous test send used by the Settings screen — throws on failure. */
    public void sendTest(String to) {
        mailDispatcher.sendNow(to, "MV Rent — test email",
                "This is a test email from MV Rent. Your SMTP settings are working.");
    }

    private static String safeName(Booking b) {
        String n = b.getUser() != null ? b.getUser().getFullName() : null;
        return (n != null && !n.isBlank()) ? n : "there";
    }
}
