package assignment

import (
	"fmt"
	"strconv"

	"doormile/db"
	"doormile/internal/notify"
	"doormile/models"
	"doormile/utils"
)

// notifyMilerNewAssignment sends an FCM push to the miler when a booking is assigned.
// Non-fatal: failure is logged but never blocks the assignment flow.
func notifyMilerNewAssignment(profile models.MilerProfile, bookingID int) {
	if profile.Devicetoken == "" {
		return
	}
	if err := notify.SendToDevice(
		profile.Devicetoken,
		"New Pickup Assigned",
		"New booking assigned — tap to view details",
		map[string]string{"booking_id": strconv.Itoa(bookingID)},
	); err != nil {
		utils.Warn("FCM: failed to notify miler on assignment",
			"miler_id", profile.Userid,
			"booking_id", bookingID,
			"error", err,
		)
	}
}

// notifyCustomerMilerAssigned sends an FCM push to the customer when their miler is assigned.
// Loads the customer's device token from DB. Non-fatal on any failure.
func notifyCustomerMilerAssigned(booking *models.PickupBooking, milerName string) {
	var customer models.AppCustomer
	if err := db.DB.Where("appcustomerid = ?", booking.Appcustomerid).First(&customer).Error; err != nil {
		return
	}
	if customer.Devicetoken == "" {
		return
	}
	if err := notify.SendToDevice(
		customer.Devicetoken,
		"Miler Assigned",
		fmt.Sprintf("Miler assigned — %s is on the way", milerName),
		map[string]string{"booking_id": strconv.Itoa(booking.Bookingid)},
	); err != nil {
		utils.Warn("FCM: failed to notify customer on assignment",
			"customer_id", booking.Appcustomerid,
			"booking_id", booking.Bookingid,
			"error", err,
		)
	}
}
