import pytest
from fastapi.testclient import TestClient
from sqlmodel import Session, SQLModel, create_engine
from sqlmodel.pool import StaticPool
from datetime import date, datetime, timedelta
from main import app
from db import get_session
from app.models.RentersInsuranceModel import RentersInsuranceModel

# Test database setup
@pytest.fixture(name="session")
def session_fixture():
    engine = create_engine(
        "sqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    SQLModel.metadata.create_all(engine)
    with Session(engine) as session:
        yield session

@pytest.fixture(name="client")
def client_fixture(session: Session):
    def get_session_override():
        return session
    
    app.dependency_overrides[get_session] = get_session_override
    client = TestClient(app)
    yield client
    app.dependency_overrides.clear()

# Test data
@pytest.fixture
def sample_renters_insurance_data():
    return {
        "property_address": "123 Main Street Apt 4B",
        "city": "Los Angeles",
        "state": "CA",
        "zip_code": "90210",
        "property_type": "Apartment",
        "year_built": 2010,
        "number_of_units_in_building": 50,
        "first_name": "John",
        "last_name": "Smith",
        "date_of_birth": "1990-05-15",
        "email_address": "john.smith@email.com",
        "phone_number": "(555) 123-4567",
        "occupation": "Software Engineer",
        "marital_status": "Single",
        "number_of_occupants": 1,
        "personal_property_coverage": 25000.0,
        "liability_coverage": 300000.0,
        "medical_payments_coverage": 5000.0,
        "deductible": 500.0,
        "loss_of_use_coverage": 10000.0,
        "replacement_cost_coverage": True,
        "scheduled_personal_property": [
            {"item": "Laptop", "value": 2000.0},
            {"item": "Jewelry", "value": 1500.0}
        ],
        "policy_term": "12 months",
        "preferred_start_date": (date.today() + timedelta(days=7)).isoformat(),
        "payment_plan": "Monthly",
        "payment_method": "ACH",
        "auto_pay_enrollment": True,
        "security_system_present": True,
        "sprinkler_system": False,
        "smoke_detectors": True,
        "claims_in_past_5_years": 0,
        "prior_carrier": None,
        "prior_policy_expiration_date": None,
        "pet_ownership": False,
        "dog_breed": None,
        "roommates_present": False,
        "landlord_information": "ABC Property Management",
        "additional_insured": "ABC Property Management"
    }

class TestRentersInsuranceAPI:
    """Test Renters Insurance API endpoints"""
    
    def test_create_renters_insurance_success(self, client: TestClient, sample_renters_insurance_data):
        """Test successful renters insurance quote creation"""
        response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        assert response.status_code == 200
        
        data = response.json()
        assert data["first_name"] == sample_renters_insurance_data["first_name"]
        assert data["last_name"] == sample_renters_insurance_data["last_name"]
        assert data["email_address"] == sample_renters_insurance_data["email_address"]
        assert data["personal_property_coverage"] == sample_renters_insurance_data["personal_property_coverage"]
        assert data["quote_status"] == "Draft"
        assert "id" in data
        assert "created_at" in data
    
    def test_create_renters_insurance_invalid_age(self, client: TestClient, sample_renters_insurance_data):
        """Test renters insurance creation with invalid age"""
        sample_renters_insurance_data["date_of_birth"] = "2010-01-01"  # Too young
        response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        assert response.status_code == 422
        assert "at least 18 years old" in response.json()["detail"][0]["msg"]
    
    def test_create_renters_insurance_invalid_zip(self, client: TestClient, sample_renters_insurance_data):
        """Test renters insurance creation with invalid ZIP code"""
        sample_renters_insurance_data["zip_code"] = "ABCDE"  # Invalid ZIP
        response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        assert response.status_code == 422
        assert "digits" in response.json()["detail"][0]["msg"]
    
    def test_create_renters_insurance_past_start_date(self, client: TestClient, sample_renters_insurance_data):
        """Test renters insurance creation with past start date"""
        sample_renters_insurance_data["preferred_start_date"] = "2020-01-01"  # Past date
        response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        assert response.status_code == 422
        assert "cannot be in the past" in response.json()["detail"][0]["msg"]
    
    def test_get_renters_insurance_success(self, client: TestClient, sample_renters_insurance_data):
        """Test successful retrieval of renters insurance quote"""
        # Create a quote first
        create_response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        quote_id = create_response.json()["id"]
        
        # Retrieve the quote
        response = client.get(f"/api/v1/renters-insurance/{quote_id}")
        assert response.status_code == 200
        
        data = response.json()
        assert data["id"] == quote_id
        assert data["first_name"] == sample_renters_insurance_data["first_name"]
        assert data["personal_property_coverage"] == sample_renters_insurance_data["personal_property_coverage"]
    
    def test_get_renters_insurance_not_found(self, client: TestClient):
        """Test retrieval of non-existent renters insurance quote"""
        response = client.get("/api/v1/renters-insurance/999")
        assert response.status_code == 404
        assert "not found" in response.json()["detail"]
    
    def test_get_all_renters_insurance_quotes(self, client: TestClient, sample_renters_insurance_data):
        """Test retrieval of all renters insurance quotes"""
        # Create multiple quotes
        client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        
        sample_renters_insurance_data["first_name"] = "Jane"
        sample_renters_insurance_data["email_address"] = "jane.doe@email.com"
        client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        
        # Get all quotes
        response = client.get("/api/v1/renters-insurance/")
        assert response.status_code == 200
        
        data = response.json()
        assert len(data) == 2
        assert all("id" in quote for quote in data)
    
    def test_update_renters_insurance_success(self, client: TestClient, sample_renters_insurance_data):
        """Test successful update of renters insurance quote"""
        # Create a quote first
        create_response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        quote_id = create_response.json()["id"]
        
        # Update the quote
        update_data = {
            "personal_property_coverage": 35000.0,
            "liability_coverage": 500000.0,
            "quote_status": "Pending"
        }
        response = client.put(f"/api/v1/renters-insurance/{quote_id}", json=update_data)
        assert response.status_code == 200
        
        data = response.json()
        assert data["personal_property_coverage"] == 35000.0
        assert data["liability_coverage"] == 500000.0
        assert data["quote_status"] == "Pending"
    
    def test_update_renters_insurance_not_found(self, client: TestClient):
        """Test update of non-existent renters insurance quote"""
        update_data = {"personal_property_coverage": 35000.0}
        response = client.put("/api/v1/renters-insurance/999", json=update_data)
        assert response.status_code == 404
        assert "not found" in response.json()["detail"]
    
    def test_delete_renters_insurance_success(self, client: TestClient, sample_renters_insurance_data):
        """Test successful deletion of renters insurance quote"""
        # Create a quote first
        create_response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        quote_id = create_response.json()["id"]
        
        # Delete the quote
        response = client.delete(f"/api/v1/renters-insurance/{quote_id}")
        assert response.status_code == 200
        assert "deleted successfully" in response.json()["message"]
        
        # Verify it's deleted
        get_response = client.get(f"/api/v1/renters-insurance/{quote_id}")
        assert get_response.status_code == 404
    
    def test_delete_renters_insurance_not_found(self, client: TestClient):
        """Test deletion of non-existent renters insurance quote"""
        response = client.delete("/api/v1/renters-insurance/999")
        assert response.status_code == 404
        assert "not found" in response.json()["detail"]
    
    def test_search_by_name(self, client: TestClient, sample_renters_insurance_data):
        """Test search by applicant name"""
        # Create a quote
        client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        
        # Search by name
        response = client.get("/api/v1/renters-insurance/search/name/John")
        assert response.status_code == 200
        
        data = response.json()
        assert len(data) >= 1
        assert data[0]["first_name"] == "John"
    
    def test_search_by_email(self, client: TestClient, sample_renters_insurance_data):
        """Test search by email address"""
        # Create a quote
        client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        
        # Search by email
        response = client.get("/api/v1/renters-insurance/search/email/john.smith@email.com")
        assert response.status_code == 200
        
        data = response.json()
        assert len(data) >= 1
        assert data[0]["email_address"] == "john.smith@email.com"
    
    def test_filter_by_status(self, client: TestClient, sample_renters_insurance_data):
        """Test filter by quote status"""
        # Create a quote
        client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        
        # Filter by status
        response = client.get("/api/v1/renters-insurance/filter/status/Draft")
        assert response.status_code == 200
        
        data = response.json()
        assert len(data) >= 1
        assert all(quote["quote_status"] == "Draft" for quote in data)
    
    def test_filter_by_property_type(self, client: TestClient, sample_renters_insurance_data):
        """Test filter by property type"""
        # Create a quote
        client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        
        # Filter by property type
        response = client.get("/api/v1/renters-insurance/filter/property-type/Apartment")
        assert response.status_code == 200
        
        data = response.json()
        assert len(data) >= 1
        assert all(quote["property_type"] == "Apartment" for quote in data)
    
    def test_filter_by_state(self, client: TestClient, sample_renters_insurance_data):
        """Test filter by state"""
        # Create a quote
        client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        
        # Filter by state
        response = client.get("/api/v1/renters-insurance/filter/state/CA")
        assert response.status_code == 200
        
        data = response.json()
        assert len(data) >= 1
        assert all(quote["state"] == "CA" for quote in data)
    
    def test_filter_by_coverage_amount(self, client: TestClient, sample_renters_insurance_data):
        """Test filter by coverage amount range"""
        # Create a quote
        client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        
        # Filter by coverage amount
        response = client.get("/api/v1/renters-insurance/filter/coverage?min_amount=20000&max_amount=30000")
        assert response.status_code == 200
        
        data = response.json()
        assert len(data) >= 1
        assert all(20000 <= quote["personal_property_coverage"] <= 30000 for quote in data)
    
    def test_filter_by_coverage_amount_invalid_range(self, client: TestClient):
        """Test filter by coverage amount with invalid range"""
        response = client.get("/api/v1/renters-insurance/filter/coverage?min_amount=30000&max_amount=20000")
        assert response.status_code == 400
        assert "cannot be greater than" in response.json()["detail"]

class TestRentersInsuranceValidation:
    """Test Renters Insurance data validation"""
    
    def test_required_fields_validation(self, client: TestClient):
        """Test validation of required fields"""
        incomplete_data = {
            "first_name": "John",
            "last_name": "Smith",
            "email_address": "john@email.com"
            # Missing required fields
        }
        
        response = client.post("/api/v1/renters-insurance/", json=incomplete_data)
        assert response.status_code == 422
        
        errors = response.json()["detail"]
        required_fields = ["property_address", "city", "state", "zip_code", "property_type", 
                          "date_of_birth", "personal_property_coverage", "liability_coverage", 
                          "deductible", "policy_term", "preferred_start_date"]
        error_fields = [error["loc"][-1] for error in errors if error["type"] == "missing"]
        
        for field in required_fields:
            assert field in error_fields
    
    def test_email_validation(self, client: TestClient, sample_renters_insurance_data):
        """Test email format validation"""
        sample_renters_insurance_data["email_address"] = "invalid-email"
        
        response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        assert response.status_code == 422
        assert "email" in str(response.json()["detail"]).lower()
    
    def test_coverage_amount_validation(self, client: TestClient, sample_renters_insurance_data):
        """Test coverage amount validation"""
        sample_renters_insurance_data["personal_property_coverage"] = 1000.0  # Below minimum
        
        response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        assert response.status_code == 422
        assert "5000" in str(response.json()["detail"])
    
    def test_pet_ownership_dog_breed_validation(self, client: TestClient, sample_renters_insurance_data):
        """Test dog breed validation when pet ownership is true"""
        sample_renters_insurance_data["pet_ownership"] = True
        sample_renters_insurance_data["dog_breed"] = None  # Should be required
        
        response = client.post("/api/v1/renters-insurance/", json=sample_renters_insurance_data)
        assert response.status_code == 422
        assert "required when pet ownership is true" in str(response.json()["detail"])

if __name__ == "__main__":
    pytest.main([__file__])