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

# 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_life_insurance_data():
    return {
        "full_name": "John Smith",
        "date_of_birth": "1985-05-15",
        "gender": "Male",
        "email_address": "john.smith@email.com",
        "phone_number": "(555) 123-4567",
        "state": "CA",
        "zip_code": "90210",
        "marital_status": "Married",
        "ssn_last4": "1234",
        "address_line1": "123 Main Street",
        "address_line2": "Apt 4B",
        "city": "Los Angeles",
        "employment_status": "Employed",
        "occupation": "Software Engineer",
        "annual_income": 85000.0,
        "height": "6'0\"",
        "weight": 180.0,
        "tobacco_use": False,
        "alcohol_consumption": "Occasional",
        "existing_conditions": ["None"],
        "medications": ["Multivitamin"],
        "family_history": ["Diabetes"],
        "coverage_amount": 500000.0,
        "coverage_term": "20 Year Term",
        "product_type": "Term Life",
        "premium_budget": 100.0,
        "payment_frequency": "Monthly",
        "riders": ["Accidental Death", "Disability Waiver"],
        "primary_beneficiary_name": "Jane Smith",
        "primary_beneficiary_relationship": "Spouse",
        "beneficiary_percentage": 100.0,
        "contingent_beneficiary_name": "John Smith Jr.",
        "contingent_beneficiary_relationship": "Child",
        "citizenship_status": "US Citizen",
        "country_of_citizenship": "United States",
        "us_citizen": True,
        "criminal_record": False,
        "bankruptcy_history": False,
        "consent_to_contact": True,
        "consent_to_share_data": True,
        "signature": "John Smith"
    }

class TestLifeInsuranceAPI:
    """Test Life Insurance API endpoints"""
    
    def test_create_life_insurance_success(self, client: TestClient, sample_life_insurance_data):
        """Test successful life insurance quote creation"""
        response = client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        assert response.status_code == 200
        
        data = response.json()
        assert data["full_name"] == sample_life_insurance_data["full_name"]
        assert data["email_address"] == sample_life_insurance_data["email_address"]
        assert data["coverage_amount"] == sample_life_insurance_data["coverage_amount"]
        assert data["quote_status"] == "Draft"
        assert "id" in data
        assert "created_at" in data
    
    def test_create_life_insurance_invalid_age(self, client: TestClient, sample_life_insurance_data):
        """Test life insurance creation with invalid age"""
        sample_life_insurance_data["date_of_birth"] = "2010-01-01"  # Too young
        response = client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        assert response.status_code == 422
        assert "at least 18 years old" in response.json()["detail"][0]["msg"]
    
    def test_create_life_insurance_invalid_percentage(self, client: TestClient, sample_life_insurance_data):
        """Test life insurance creation with invalid beneficiary percentage"""
        sample_life_insurance_data["beneficiary_percentage"] = 150.0  # Invalid percentage
        response = client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        assert response.status_code == 422
        msg = response.json()["detail"][0]["msg"]
        assert "between 1 and 100" in msg or "less than or equal to 100" in msg
    
    def test_get_life_insurance_success(self, client: TestClient, sample_life_insurance_data):
        """Test successful retrieval of life insurance quote"""
        # Create a quote first
        create_response = client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        quote_id = create_response.json()["id"]
        
        # Retrieve the quote
        response = client.get(f"/api/v1/life-insurance/{quote_id}")
        assert response.status_code == 200
        
        data = response.json()
        assert data["id"] == quote_id
        assert data["full_name"] == sample_life_insurance_data["full_name"]
        assert data["coverage_amount"] == sample_life_insurance_data["coverage_amount"]
    
    def test_get_life_insurance_not_found(self, client: TestClient):
        """Test retrieval of non-existent life insurance quote"""
        response = client.get("/api/v1/life-insurance/999")
        assert response.status_code == 404
        assert "not found" in response.json()["detail"]
    
    def test_get_all_life_insurance_quotes(self, client: TestClient, sample_life_insurance_data):
        """Test retrieval of all life insurance quotes"""
        # Create multiple quotes
        client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        
        sample_life_insurance_data["full_name"] = "Jane Doe"
        sample_life_insurance_data["email_address"] = "jane.doe@email.com"
        client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        
        # Get all quotes
        response = client.get("/api/v1/life-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_life_insurance_success(self, client: TestClient, sample_life_insurance_data):
        """Test successful update of life insurance quote"""
        # Create a quote first
        create_response = client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        quote_id = create_response.json()["id"]
        
        # Update the quote
        update_data = {
            "coverage_amount": 750000.0,
            "premium_budget": 150.0,
            "quote_status": "Pending"
        }
        response = client.put(f"/api/v1/life-insurance/{quote_id}", json=update_data)
        assert response.status_code == 200
        
        data = response.json()
        assert data["coverage_amount"] == 750000.0
        assert data["premium_budget"] == 150.0
        assert data["quote_status"] == "Pending"
    
    def test_update_life_insurance_not_found(self, client: TestClient):
        """Test update of non-existent life insurance quote"""
        update_data = {"coverage_amount": 750000.0}
        response = client.put("/api/v1/life-insurance/999", json=update_data)
        assert response.status_code == 404
        assert "not found" in response.json()["detail"]
    
    def test_delete_life_insurance_success(self, client: TestClient, sample_life_insurance_data):
        """Test successful deletion of life insurance quote"""
        # Create a quote first
        create_response = client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        quote_id = create_response.json()["id"]
        
        # Delete the quote
        response = client.delete(f"/api/v1/life-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/life-insurance/{quote_id}")
        assert get_response.status_code == 404
    
    def test_delete_life_insurance_not_found(self, client: TestClient):
        """Test deletion of non-existent life insurance quote"""
        response = client.delete("/api/v1/life-insurance/999")
        assert response.status_code == 404
        assert "not found" in response.json()["detail"]
    
    def test_search_by_name(self, client: TestClient, sample_life_insurance_data):
        """Test search by applicant name"""
        # Create a quote
        client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        
        # Search by name
        response = client.get("/api/v1/life-insurance/search/name/John Smith")
        assert response.status_code == 200
        
        data = response.json()
        assert len(data) >= 1
        assert data[0]["full_name"] == "John Smith"
    
    def test_search_by_email(self, client: TestClient, sample_life_insurance_data):
        """Test search by email address"""
        # Create a quote
        client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        
        # Search by email
        response = client.get("/api/v1/life-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_life_insurance_data):
        """Test filter by quote status"""
        # Create a quote
        client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        
        # Filter by status
        response = client.get("/api/v1/life-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_coverage_amount(self, client: TestClient, sample_life_insurance_data):
        """Test filter by coverage amount range"""
        # Create a quote
        client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        
        # Filter by coverage amount
        response = client.get("/api/v1/life-insurance/filter/coverage?min_amount=400000&max_amount=600000")
        assert response.status_code == 200
        
        data = response.json()
        assert len(data) >= 1
        assert all(400000 <= quote["coverage_amount"] <= 600000 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/life-insurance/filter/coverage?min_amount=600000&max_amount=400000")
        assert response.status_code == 400
        assert "cannot be greater than" in response.json()["detail"]

class TestLifeInsuranceValidation:
    """Test Life Insurance data validation"""
    
    def test_required_fields_validation(self, client: TestClient):
        """Test validation of required fields"""
        incomplete_data = {
            "full_name": "John Smith",
            "email_address": "john@email.com"
            # Missing required fields
        }
        
        response = client.post("/api/v1/life-insurance/", json=incomplete_data)
        assert response.status_code == 422
        
        errors = response.json()["detail"]
        required_fields = ["date_of_birth", "gender", "phone_number", "state", "zip_code"]
        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_life_insurance_data):
        """Test email format validation"""
        sample_life_insurance_data["email_address"] = "invalid-email"
        
        response = client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        assert response.status_code == 422
        assert "email" in str(response.json()["detail"]).lower()
    
    def test_coverage_amount_validation(self, client: TestClient, sample_life_insurance_data):
        """Test coverage amount validation"""
        sample_life_insurance_data["coverage_amount"] = 10000.0  # Below minimum
        
        response = client.post("/api/v1/life-insurance/", json=sample_life_insurance_data)
        assert response.status_code == 422
        assert "25000" in str(response.json()["detail"])

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