import pytest
from fastapi import HTTPException

from api.v1.modules.crm.accounts import service as accounts_service
from api.v1.modules.crm.accounts.dto import AccountCreate
from api.v1.modules.crm.quotes import service as quotes_service
from api.v1.modules.crm.quotes.dto import QuoteCreate
from api.v1.modules.crm.service_requests import service as sr_service
from api.v1.modules.crm.service_requests.dto import ServiceRequestCreate
from api.v1.modules.ops.shipments import service
from api.v1.modules.ops.shipments.dto import ShipmentCreate, ShipmentDocumentCreate

T, C = 1, 1


def test_release_requires_accepted_quote(db):
    q = quotes_service.create_quote(db, QuoteCreate(reference="COT-A"), T, C)
    with pytest.raises(HTTPException) as exc:
        service.create_shipment_from_quote(db, q.id, T, C)
    assert exc.value.status_code == 422  # aún no aceptada


def test_release_from_accepted_quote_copies_data(db):
    acc = accounts_service.create_account(db, AccountCreate(name="Cliente"), T, C)
    sr = sr_service.create_service_request(
        db,
        ServiceRequestCreate(account_id=acc.id, operation_type="exportacion", transport_mode="maritimo",
                             origin="Veracruz", destination="Rotterdam"),
        T, C,
    )
    q = quotes_service.create_quote(db, QuoteCreate(reference="COT-B", service_request_id=sr.id, account_id=acc.id), T, C)
    quotes_service.accept_quote(db, q.id, T, C)

    shipment = service.create_shipment_from_quote(db, q.id, T, C, user_id="dev")
    assert shipment.quote_id == q.id
    assert shipment.account_id == acc.id
    assert shipment.operation_type == "exportacion"
    assert shipment.transport_mode == "maritimo"
    assert shipment.origin == "Veracruz"
    assert shipment.status == "abierta"
    # la solicitud queda liberada
    sr = sr_service.get_service_request(db, sr.id, T, C)
    assert sr.status == "liberada"


def test_shipment_crud_and_documents(db):
    shipment = service.create_shipment(db, ShipmentCreate(reference="EMB-001", status="abierta", origin="MX"), T, C)
    assert shipment.id is not None
    doc = service.create_shipment_document(
        db, ShipmentDocumentCreate(shipment_id=shipment.id, doc_kind="master", doc_type="MBL", number="MBL123"), T, C
    )
    assert doc.doc_type == "MBL"
    docs = service.get_shipment_documents(db, T, C, shipment_id=shipment.id)
    assert len(docs) == 1


def test_shipment_rejects_unknown_quote(db):
    with pytest.raises(HTTPException) as exc:
        service.create_shipment(db, ShipmentCreate(quote_id=999), T, C)
    assert exc.value.status_code == 422


# ----- Cotización → Operación: dirección IMPO/EXPO + auto-hitos + folio OP -----

def _accepted_quote(db, sr=None):
    kwargs = {"reference": "COT-Z"}
    if sr is not None:
        kwargs["service_request_id"] = sr.id
    q = quotes_service.create_quote(db, QuoteCreate(**kwargs), T, C)
    quotes_service.accept_quote(db, q.id, T, C)
    return q


def test_from_quote_explicit_operation_type_generates_milestones(db):
    q = _accepted_quote(db)
    shipment = service.create_shipment_from_quote(db, q.id, T, C, operation_type="importacion")
    assert shipment.operation_type == "importacion"
    assert shipment.reference.startswith("OP") and shipment.reference.endswith("-I")
    events = service.get_shipment_events(db, T, C, shipment.id)
    assert len(events) == 11  # hitos de importación (Diagrama 3)


def test_from_quote_inherits_sr_operation_type(db):
    sr = sr_service.create_service_request(db, ServiceRequestCreate(operation_type="exportacion"), T, C)
    q = _accepted_quote(db, sr=sr)
    shipment = service.create_shipment_from_quote(db, q.id, T, C)  # sin operation_type explícito
    assert shipment.operation_type == "exportacion"
    events = service.get_shipment_events(db, T, C, shipment.id)
    assert len(events) == 19  # hitos de exportación (Diagrama 2)


def test_from_quote_no_operation_type_no_milestones(db):
    q = _accepted_quote(db)  # sin solicitud → sin dirección
    shipment = service.create_shipment_from_quote(db, q.id, T, C)
    assert shipment.operation_type is None
    assert service.get_shipment_events(db, T, C, shipment.id) == []  # sin hitos, sin excepción
    assert shipment.reference.endswith("-X")


def test_from_quote_invalid_operation_type(db):
    q = _accepted_quote(db)
    with pytest.raises(HTTPException) as exc:
        service.create_shipment_from_quote(db, q.id, T, C, operation_type="foo")
    assert exc.value.status_code == 422
