import pytest
from fastapi.testclient import TestClient
from datetime import date

def test_business_umbrella_validation_and_update(client: TestClient):
    # 1. Valid Creation
    payload = {
        "business_name": "Acme Corp",
        "contact_name": "John Doe",
        "email_address": "john.doe@example.com",
        "phone_number": "(123) 456-7890",
        "business_address": "123 Main St",
        "type_of_business": "Technology",
        "number_of_employees": 10,
        "years_in_operation": 5,
        "annual_revenue": 1000000.0,
        "existing_liability_policies": ["General Liability"],
        "total_liability_limits": 1000000.0,
        "desired_umbrella_coverage": 2000000.0,
        "high_risk_operations": False,
        "past_liability_claims": False,
        "pending_lawsuits": False,
        "locations_of_operations": ["CA"],
        "desired_policy_start_date": "2026-07-01"
    }
    response = client.post("/api/v1/businessumbrella/", json=payload)
    assert response.status_code == 200
    data = response.json()
    assert "transaction_no" in data
    product_id = data["id"]

    # 2. Invalid phone number pattern validation (should now succeed and normalize)
    payload["phone_number"] = "123-456-7890"  # Expected pattern is (123) 456-7890
    response = client.post("/api/v1/businessumbrella/", json=payload)
    assert response.status_code == 200
    created_id = response.json()["id"]
    get_resp = client.get(f"/api/v1/businessumbrella/{created_id}")
    assert get_resp.status_code == 200
    assert get_resp.json()["phone_number"] == "(123) 456-7890"

    # 3. Partial Update via PUT
    update_payload = {"phone_number": "(987) 654-3210"}
    response = client.put(f"/api/v1/businessumbrella/{product_id}", json=update_payload)
    print("PUT RESPONSE JSON:", response.json())
    assert response.status_code == 200
    assert response.json()["phone_number"] == "(987) 654-3210"


def test_home_insurance_validation_and_update(client: TestClient):
    # 1. Invalid zip code pattern validation (should fail)
    payload = {
        "first_name": "John",
        "last_name": "Doe",
        "date_of_birth": "1990-01-01",
        "phone_number": "1234567890",
        "email": "john@example.com",
        "property_address": "123 Oak St",
        "city": "San Francisco",
        "state": "CA",
        "zip_code": "941031",  # Invalid zip code (6 digits instead of 5)
        "property_type": "Single Family",
        "year_built": 2000,
        "square_footage": 1500,
        "construction_type": "Frame",
        "primary_residence": True,
        "occupancy_type": "Owner",
        "desired_coverage_start_date": "2026-07-01"
    }
    response = client.post("/api/v1/homeinsurance/", json=payload)
    assert response.status_code == 422

    # 2. Correct the zip code and verify successful creation
    payload["zip_code"] = "94103"
    response = client.post("/api/v1/homeinsurance/", json=payload)
    assert response.status_code == 200
    product_id = response.json()["id"]

    # 3. Partial Update
    update_payload = {"square_footage": 1800}
    response = client.put(f"/api/v1/homeinsurance/{product_id}", json=update_payload)
    assert response.status_code == 200
    assert response.json()["square_footage"] == 1800


def test_personal_auto_insurance_validation_and_update(client: TestClient):
    # 1. Valid Creation
    payload = {
        "first_name": "John",
        "last_name": "Doe",
        "date_of_birth": "1990-01-01",
        "driver_license_number": "DL12345",
        "license_state": "CA",
        "years_licensed": 5,
        "email": "john@example.com",
        "phone_number": "1234567890",
        "street_address": "123 Main St",
        "city": "Los Angeles",
        "state": "CA",
        "zip_code": "90210",
        "vehicle_year": 2015,
        "make": "Toyota",
        "model": "Camry",
        "annual_mileage": 12000,
        "garaging_zip": "90210",
        "number_of_drivers": 1,
        "relationship_to_applicant": "Self",
        "driver_name": "John Doe",
        "driver_dob": "1990-01-01",
        "license_number": "DL12345",
        "driver_years_licensed": 5,
        "coverage_type": "Standard",
        "bodily_injury_liability": "100k/300k",
        "property_damage_liability": "100k",
        "currently_insured": True,
        "occupation": "Engineer",
        "medical_payments": "5000",
        "current_carrier": "Geico",
        "policy_expiration_date": "2026-12-31",
        "prior_lapse": False,
        "payment_preference": "Monthly",
        "preferred_quote_delivery": "Email",
        "agent_id": "AGT123",
        "source_platform": "Web",
        "quote_reference_id": "REF123"
    }
    response = client.post("/api/v1/personalautoinsurance/", json=payload)
    print("PERSONAL AUTO RESP:", response.json())
    assert response.status_code == 200
    data = response.json()
    assert "transaction_no" in data
    product_id = data["id"]

    # 2. Invalid zip code (should fail)
    payload["zip_code"] = "902100"
    response = client.post("/api/v1/personalautoinsurance/", json=payload)
    assert response.status_code == 422

    # 3. Partial Update
    update_payload = {"annual_mileage": 15000}
    response = client.put(f"/api/v1/personalautoinsurance/{product_id}", json=update_payload)
    assert response.status_code == 200
    assert response.json()["annual_mileage"] == 15000


def test_input_normalization_fixes(client: TestClient):
    # 1. Test Group Health normalization
    group_health_payload = {
        "company_name": "Test Group Health",
        "industry_sic_code": "1234",
        "company_address": "123 Test St",
        "city": "Miami",
        "state": "Florida",              # Needs normalization to "FL"
        "zip_code": "33101",
        "federal_tax_id": "12-3456789",  # Needs normalization to "123456789"
        "number_of_employees": 10,
        "number_of_employees_to_be_covered": 8,
        "type_of_coverage_requested": "PPO",
        "desired_coverage_start_date": "2026-08-01",
        "broker_agent_involved": False,
        "contact_person_name": "John Tester",
        "contact_email": "john@testgroup.com",
        "contact_phone": "3051234567",   # Needs normalization to "(305) 123-4567"
        "transaction_no": "TXG12345"
    }
    response = client.post("/api/v1/group-health/quotes", json=group_health_payload)
    assert response.status_code == 201, f"Group Health creation failed: {response.text}"
    gh_data = response.json()
    assert gh_data["state"] == "FL"
    assert gh_data["federal_tax_id"] == "123456789"
    assert gh_data["contact_phone"] == "(305) 123-4567"

    # 2. Test General Liability normalization
    general_liability_payload = {
        "business_name": "Test General Liability",
        "contact_name": "Jane Tester",
        "email_address": "jane@testgl.com",
        "phone_number": "123-456-7890",  # Needs normalization to "(123) 456-7890"
        "business_address": "456 Oak Ave",
        "type_of_business": "Consulting",
        "years_in_business": 3,
        "number_of_employees": 5,
        "estimated_annual_revenue": 500000.0,
        "primary_business_activities": "IT Consulting",
        "premises_owned_or_leased": "Leased",
        "subcontractors_used": False,
        "states_of_operation": ["Florida", "ca"],  # Needs normalization to ["FL", "CA"]
        "customers_visit_location": False,
        "past_liability_claims": False,
        "desired_coverage_limit": 1000000.0,
        "desired_policy_start_date": "2026-08-01",
        "transaction_no": "TXGL12345"
    }
    response = client.post("/api/v1/generalliability/", json=general_liability_payload)
    assert response.status_code == 200, f"General Liability creation failed: {response.text}"
    gl_id = response.json()["id"]

    # Verify normalization via GET
    get_resp = client.get(f"/api/v1/generalliability/{gl_id}")
    assert get_resp.status_code == 200
    gl_data = get_resp.json()
    assert gl_data["phone_number"] == "(123) 456-7890"
    assert gl_data["states_of_operation"] == ["FL", "CA"]

