from decimal import Decimal


def test_login_success(client, seed_data):
    response = client.post("/api/v1/auth/login", json={"email": "admin@test.com", "password": "Test@12345"})
    assert response.status_code == 200
    body = response.json()
    assert "access_token" in body
    assert "refresh_token" in body


def test_login_invalid_password(client, seed_data):
    response = client.post("/api/v1/auth/login", json={"email": "admin@test.com", "password": "wrong1"})
    assert response.status_code == 401


def test_policies_requires_auth(client, seed_data):
    response = client.get("/api/v1/policies")
    assert response.status_code == 401


def test_policies_list(client, auth_headers, seed_data):
    response = client.get("/api/v1/policies", headers=auth_headers)
    assert response.status_code == 200
    body = response.json()
    assert body["total"] == 1
    assert body["items"][0]["policy_number"] == "POL-TEST-001"


def test_policy_detail(client, auth_headers, seed_data):
    policy_id = seed_data["policy"].id
    response = client.get(f"/api/v1/policies/{policy_id}", headers=auth_headers)
    assert response.status_code == 200
    assert response.json()["customer_name"] == "Ramesh Kumar"


def test_add_payment_updates_pending(client, auth_headers, seed_data):
    policy_id = seed_data["policy"].id
    response = client.post(
        f"/api/v1/policies/{policy_id}/payments",
        headers=auth_headers,
        json={
            "amount": 400,
            "payment_date": "2026-06-26",
            "payment_mode": "upi",
            "reference_number": "TXN123",
        },
    )
    assert response.status_code == 200

    policy = client.get(f"/api/v1/policies/{policy_id}", headers=auth_headers).json()
    assert Decimal(str(policy["total_paid"])) == Decimal("400.00")
    assert Decimal(str(policy["pending_amount"])) == Decimal("600.00")
    assert policy["payment_status"] == "partial"

    payments = client.get(f"/api/v1/policies/{policy_id}/payments", headers=auth_headers).json()
    assert len(payments) == 1
