from django.utils import timezone

from MASTERAPP.models import Shipment

from MASTERAPP.services.order_tracking_service import (
    create_tracking_event,
)


SHIPMENT_TRACKING_MAP = {

    "ready_to_ship": {
        "title": "Ready To Ship",
        "description": "Your shipment is ready to ship.",
        "order_status": "processing",
    },

    "shipped": {
        "title": "Shipment Shipped",
        "description": "Your shipment has been shipped.",
        "order_status": "shipped",
    },

    "in_transit": {
        "title": "In Transit",
        "description": "Your shipment is in transit.",
        "order_status": "shipped",
    },

    "out_for_delivery": {
        "title": "Out For Delivery",
        "description": "Your shipment is out for delivery.",
        "order_status": "out_for_delivery",
    },

    "delivered": {
        "title": "Delivered",
        "description": "Your shipment has been delivered.",
        "order_status": "delivered",
    },
}


def update_shipment_status(
    shipment,
    shipment_status,
):

    config = SHIPMENT_TRACKING_MAP.get(
        shipment_status,
    )

    shipment.shipment_status = shipment_status

    if shipment_status == "shipped":

        shipment.shipped_at = timezone.now()

    elif shipment_status == "delivered":

        shipment.delivered_at = timezone.now()

    shipment.save()

    if not config:
        return shipment

    order = shipment.order

    order.status = config["order_status"]

    order.save()

    create_tracking_event(
        order=order,
        status=shipment_status,
        title=config["title"],
        description=config["description"],
    )

    return shipment