from datetime import date, timedelta
from decimal import Decimal

from app.models.enums import PaymentStatus, PolicyStatus
from app.models.policy import Policy
from app.schemas.reports import ReportFilters
from app.services.report_service import ReportService
from app.utils.report_export import export_report_pdf, export_report_xlsx


def test_list_report_types(client, auth_headers):
    response = client.get("/api/v1/reports/types", headers=auth_headers)
    assert response.status_code == 200
    types = {item["id"] for item in response.json()}
    assert "total-policies" in types
    assert "payment-summary" in types


def test_total_policies_report(client, auth_headers, seed_data):
    response = client.get("/api/v1/reports/total-policies", headers=auth_headers)
    assert response.status_code == 200
    body = response.json()
    assert body["report_type"] == "total-policies"
    assert body["summary"]["total_policies"] >= 1
    statuses = {row["status"] for row in body["rows"]}
    assert "active" in statuses


def test_expired_policies_report(client, auth_headers, db, seed_data):
    expired = Policy(
        agency_id=seed_data["agency"].id,
        customer_id=seed_data["customer"].id,
        vehicle_id=seed_data["vehicle"].id,
        policy_number="POL-EXPIRED-001",
        policy_end_date=date.today() - timedelta(days=5),
        total_commission=Decimal("500"),
        total_paid=Decimal("500"),
        pending_amount=Decimal("0"),
        payment_status=PaymentStatus.PAID,
        status=PolicyStatus.EXPIRED,
    )
    db.add(expired)
    db.commit()

    response = client.get("/api/v1/reports/expired", headers=auth_headers)
    assert response.status_code == 200
    numbers = [row["policy_number"] for row in response.json()["rows"]]
    assert "POL-EXPIRED-001" in numbers


def test_payment_summary_with_filters(client, auth_headers, seed_data):
    response = client.get(
        "/api/v1/reports/payment-summary",
        headers=auth_headers,
        params={"payment_status": "pending"},
    )
    assert response.status_code == 200
    body = response.json()
    assert body["summary"]["total_pending"] >= 0
    for row in body["rows"]:
        assert row["payment_status"] == "pending"


def test_export_xlsx(client, auth_headers):
    response = client.get(
        "/api/v1/reports/total-policies/export",
        headers=auth_headers,
        params={"format": "xlsx"},
    )
    assert response.status_code == 200
    assert "spreadsheetml" in response.headers["content-type"]
    assert len(response.content) > 100


def test_export_pdf(client, auth_headers):
    response = client.get(
        "/api/v1/reports/company-wise/export",
        headers=auth_headers,
        params={"format": "pdf"},
    )
    assert response.status_code == 200
    assert response.headers["content-type"] == "application/pdf"
    assert response.content[:4] == b"%PDF"


def test_unknown_report_type(client, auth_headers):
    response = client.get("/api/v1/reports/not-a-report", headers=auth_headers)
    assert response.status_code == 422 or response.status_code == 400


def test_reports_require_auth(client):
    response = client.get("/api/v1/reports/total-policies")
    assert response.status_code == 401


def test_report_service_monthly_renewals(db, seed_data):
    old_policy = seed_data["policy"]
    new_policy = Policy(
        agency_id=seed_data["agency"].id,
        customer_id=seed_data["customer"].id,
        vehicle_id=seed_data["vehicle"].id,
        policy_number="POL-NEW-001",
        policy_end_date=date.today() + timedelta(days=365),
        total_commission=Decimal("1200"),
        total_paid=Decimal("0"),
        pending_amount=Decimal("1200"),
        payment_status=PaymentStatus.PENDING,
        status=PolicyStatus.ACTIVE,
    )
    db.add(new_policy)
    db.flush()
    old_policy.status = PolicyStatus.RENEWED
    old_policy.renewed_from_policy_id = new_policy.id
    db.commit()

    report = ReportService(db).generate(seed_data["agency"].id, "monthly-renewals", ReportFilters())
    assert report.summary["total_renewals"] >= 1
    assert report.summary["total_commission"] >= 1200


def test_export_helpers():
    from app.schemas.reports import ReportColumn, ReportResponse

    sample = ReportResponse(
        report_type="total-policies",
        title="Total Policies",
        columns=[ReportColumn(key="status", label="Status"), ReportColumn(key="count", label="Count")],
        rows=[{"status": "active", "count": 3}],
        summary={"total_policies": 3},
    )
    xlsx = export_report_xlsx(sample)
    pdf = export_report_pdf(sample)
    assert len(xlsx) > 100
    assert pdf[:4] == b"%PDF"
