from decimal import Decimal

from api.v1.modules.crm.quotes import service
from api.v1.modules.crm.quotes.dto import QuoteCreate, QuoteItemCreate, QuoteItemUpdate
from api.v1.modules.crm.service_requests import service as sr_service
from api.v1.modules.crm.service_requests.dto import ServiceRequestCreate

T, C = 1, 1


def test_quote_totals_recompute_on_items(db):
    q = service.create_quote(db, QuoteCreate(reference="COT-001", currency="USD"), T, C)
    service.create_quote_item(
        db, QuoteItemCreate(quote_id=q.id, concept="flete_internacional", quantity=2, unit_cost=100, unit_sale=150), T, C
    )
    service.create_quote_item(
        db, QuoteItemCreate(quote_id=q.id, concept="despacho_aduanal", quantity=1, unit_cost=50, unit_sale=90), T, C
    )
    q = service.get_quote(db, q.id, T, C)
    assert float(q.total_cost) == 250.0  # 2*100 + 1*50
    assert float(q.total_sale) == 390.0  # 2*150 + 1*90


def test_quote_totals_update_and_delete_item(db):
    q = service.create_quote(db, QuoteCreate(reference="COT-002"), T, C)
    item = service.create_quote_item(
        db, QuoteItemCreate(quote_id=q.id, concept="otros", quantity=1, unit_cost=100, unit_sale=200), T, C
    )
    service.update_quote_item(db, item.id, QuoteItemUpdate(unit_sale=Decimal("300")), T, C)
    q = service.get_quote(db, q.id, T, C)
    assert float(q.total_sale) == 300.0
    service.delete_quote_item(db, item.id, T, C)
    q = service.get_quote(db, q.id, T, C)
    assert float(q.total_sale) == 0.0


def test_accept_quote_updates_service_request(db):
    sr = sr_service.create_service_request(db, ServiceRequestCreate(operation_type="exportacion"), T, C)
    q = service.create_quote(db, QuoteCreate(reference="COT-003", service_request_id=sr.id), T, C)
    service.send_quote(db, q.id, T, C)
    accepted = service.accept_quote(db, q.id, T, C)
    assert accepted.status == "aceptada"
    assert accepted.accepted_at is not None
    # la solicitud asociada queda aceptada
    sr = sr_service.get_service_request(db, sr.id, T, C)
    assert sr.status == "aceptada"
