from datetime import date, timedelta

from app.models.extraction_result import ExtractionResult
from app.models.enums import ExtractionStatus


def _extraction_with_fields(db, agency_id: int, *, policy_number: str | None = None, vehicle_reg: str | None = None):
    fields = []
    if policy_number:
        fields.append({"field_name": "policy_number", "value": policy_number, "confidence": 0.95})
    if vehicle_reg:
        fields.append({"field_name": "vehicle_registration_number", "value": vehicle_reg, "confidence": 0.95})
    fields.append({"field_name": "policy_end_date", "value": "2027-12-31", "confidence": 0.9})
    fields.append({"field_name": "customer_name", "value": "Queue Test Customer", "confidence": 0.9})

    extraction = ExtractionResult(
        agency_id=agency_id,
        original_filename="queue-match-test.pdf",
        status=ExtractionStatus.SUCCESS,
        raw_data={"fields": fields, "company_detection": {"name": "Test Insurer"}},
    )
    db.add(extraction)
    db.commit()
    db.refresh(extraction)
    return extraction


def test_queue_marks_existing_policy_number(client, auth_headers, seed_data, db):
    agency_id = seed_data["agency"].id
    existing_number = seed_data["policy"].policy_number
    _extraction_with_fields(db, agency_id, policy_number=existing_number)

    response = client.get("/api/v1/upload/extractions", headers=auth_headers, params={"pending": True})
    assert response.status_code == 200
    body = response.json()
    matched = next(item for item in body["items"] if item.get("policy_number") == existing_number)
    assert matched["is_new"] is False
    assert matched["policy_match"]["existing_policy_id"] == seed_data["policy"].id
    assert matched["policy_match"]["match_type"] == "policy_number"
    assert body["existing_count"] >= 1


def test_queue_marks_new_policy_number(client, auth_headers, db, seed_data):
    agency_id = seed_data["agency"].id
    _extraction_with_fields(db, agency_id, policy_number="BRAND-NEW-QUEUE-999")

    response = client.get("/api/v1/upload/extractions", headers=auth_headers, params={"pending": True})
    assert response.status_code == 200
    matched = next(item for item in response.json()["items"] if item.get("policy_number") == "BRAND-NEW-QUEUE-999")
    assert matched["is_new"] is True
    assert matched["policy_match"] is None


def test_queue_filter_new_only(client, auth_headers, db, seed_data):
    agency_id = seed_data["agency"].id
    _extraction_with_fields(db, agency_id, policy_number=seed_data["policy"].policy_number)
    _extraction_with_fields(db, agency_id, policy_number="ONLY-NEW-FILTER-001")

    response = client.get(
        "/api/v1/upload/extractions",
        headers=auth_headers,
        params={"pending": True, "queue_match": "new"},
    )
    assert response.status_code == 200
    assert all(item["is_new"] for item in response.json()["items"])
    assert any(item.get("policy_number") == "ONLY-NEW-FILTER-001" for item in response.json()["items"])


def test_extraction_detail_includes_policy_match(client, auth_headers, db, seed_data):
    agency_id = seed_data["agency"].id
    extraction = _extraction_with_fields(db, agency_id, policy_number=seed_data["policy"].policy_number)

    response = client.get(f"/api/v1/upload/extraction/{extraction.id}", headers=auth_headers)
    assert response.status_code == 200
    body = response.json()
    assert body["is_new"] is False
    assert body["policy_match"]["existing_policy_id"] == seed_data["policy"].id
