import logging
from sqlalchemy.orm import Session, joinedload
from .models import Shipment


def get_shipments(db: Session):
    logging.info("Fetching all shipments from the database.")
    shipments = (
        db.query(Shipment)
        .options(
            joinedload(Shipment.contact),
            joinedload(Shipment.return_address),
            joinedload(Shipment.proposal),
            joinedload(Shipment.dewars),
        )
        .all()
    )
    logging.info(f"Total of {len(shipments)} shipments fetched.")
    for shipment in shipments:
        if shipment.proposal_id is None:
            logging.warning(f"Shipment {shipment.id} is missing proposal ID.")
        logging.debug(
            f"Shipment ID: {shipment.id}, Shipment Name: {shipment.shipment_name}"
        )
    return shipments


def get_shipment_by_id(db: Session, id: int):
    logging.info(f"Fetching shipment with ID: {id}")
    shipment = (
        db.query(Shipment)
        .options(
            joinedload(Shipment.contact),
            joinedload(Shipment.return_address),
            joinedload(Shipment.proposal),
            joinedload(Shipment.dewars),
        )
        .filter(Shipment.id == id)
        .first()
    )
    if shipment:
        if shipment.proposal_id is None:
            logging.warning(f"Shipment {shipment.id} is missing proposal ID.")
        logging.info(f"Shipment found: {shipment}")
    else:
        logging.warning(f"Shipment with ID {id} not found.")
    return shipment
