import pytest
from fastapi.testclient import TestClient
import jwt
import os
from sqlmodel import Session, select
from app.models.user import User
from app.models.LifeInsuranceModel import LifeInsuranceModel

JWT_SECRET = os.getenv("JWT_SECRET", "super_secret_insurance_border_key")

def test_jwt_and_rbac_flow(client: TestClient, db_session: Session):
    # 1. Register a new customer
    register_payload = {
        "name": "Customer User",
        "email": "customer@example.com",
        "mobile": "1234567890",
        "role": "customer",
        "password": "Customer@Password123"
    }
    resp = client.post("/api/auth/register", json=register_payload)
    assert resp.status_code == 201
    reg_data = resp.json()
    assert "access_token" in reg_data
    assert "refresh_token" in reg_data
    assert reg_data["user"]["role"] == "customer"
    assert reg_data["user"]["mobile"] == "1234567890"

    access_token = reg_data["access_token"]
    refresh_token = reg_data["refresh_token"]

    # 2. Register another customer (ownership isolation test)
    other_register_payload = {
        "name": "Other User",
        "email": "other@example.com",
        "mobile": "0987654321",
        "role": "customer",
        "password": "Other@Password123"
    }
    resp_other = client.post("/api/auth/register", json=other_register_payload)
    assert resp_other.status_code == 201
    other_access_token = resp_other.json()["access_token"]

    # 3. Register an admin user
    admin_register_payload = {
        "name": "Admin User",
        "email": "admin@example.com",
        "mobile": "5555555555",
        "role": "admin",
        "password": "Admin@Password123"
    }
    resp_admin = client.post("/api/auth/register", json=admin_register_payload)
    assert resp_admin.status_code == 201
    admin_access_token = resp_admin.json()["access_token"]

    # 4. Fetch profile using /api/auth/me (requires JWT)
    headers = {"Authorization": f"Bearer {access_token}"}
    resp = client.get("/api/auth/me", headers=headers)
    assert resp.status_code == 200, f"Me endpoint failed: {resp.status_code} - {resp.json()}"
    assert resp.json()["email"] == "customer@example.com"

    # 5. Token refresh
    resp = client.post("/api/auth/refresh-token", json={"refresh_token": refresh_token})
    assert resp.status_code == 200
    refresh_data = resp.json()
    assert "access_token" in refresh_data
    new_access_token = refresh_data["access_token"]

    # 6. Forgot and Reset Password
    resp = client.post("/api/auth/forgot-password", json={"email": "customer@example.com"})
    assert resp.status_code == 200
    assert resp.json()["message"] == "Password reset email sent."

    # Decode reset token from db print logic (we can mock or grab from JWT)
    # Let's generate a reset token manually using same secret to simulate reset
    reset_payload = {
        "sub": str(reg_data["user"]["id"]),
        "email": "customer@example.com",
        "type": "reset"
    }
    reset_token = jwt.encode(reset_payload, JWT_SECRET, algorithm="HS256")
    
    resp = client.post("/api/auth/reset-password", json={
        "token": reset_token,
        "new_password": "NewCustomer@Password123"
    })
    assert resp.status_code == 200
    assert resp.json()["message"] == "Password has been reset successfully."

    # Verify login with new password
    resp = client.post("/api/auth/login", json={
        "email": "customer@example.com",
        "password": "NewCustomer@Password123"
    })
    assert resp.status_code == 200
    assert "access_token" in resp.json()
    new_access_token = resp.json()["access_token"]

    # 7. Create life insurance quote under Customer 1
    # Customer 1 header
    c1_headers = {"Authorization": f"Bearer {new_access_token}"}
    quote_payload = {
        "full_name": "Customer User",
        "date_of_birth": "1990-01-01",
        "gender": "Male",
        "email_address": "customer@example.com",
        "phone_number": "(123) 456-7890",
        "state": "CA",
        "zip_code": "90210",
        "marital_status": "Single",
        "address_line1": "123 Main St",
        "city": "Los Angeles",
        "employment_status": "Employed",
        "height": "6ft",
        "weight": 180.0,
        "tobacco_use": False,
        "coverage_amount": 500000.0,
        "coverage_term": "20 Year Term",
        "product_type": "Term Life",
        "premium_budget": 100.0,
        "payment_frequency": "Monthly",
        "riders": ["Accidental Death"],
        "primary_beneficiary_name": "Jane Doe",
        "primary_beneficiary_relationship": "Spouse",
        "beneficiary_percentage": 100.0,
        "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": "Customer User"
    }
    resp = client.post("/api/v1/life-insurance/", json=quote_payload, headers=c1_headers)
    assert resp.status_code == 200, f"Failed to create life insurance: {resp.status_code} - {resp.json()}"
    print("CREATED QUOTE RESP:", resp.json())
    policy_id = resp.json()["id"]

    # 8. Try to read Customer 1's quote using Customer 2's token (should return 403 Forbidden)
    c2_headers = {"Authorization": f"Bearer {other_access_token}"}
    resp = client.get(f"/api/v1/life-insurance/{policy_id}", headers=c2_headers)
    assert resp.status_code == 403
    assert resp.json()["detail"] == "You do not have permission to access this resource."

    # 9. Read Customer 1's quote using Admin token (should succeed)
    admin_headers = {"Authorization": f"Bearer {admin_access_token}"}
    resp = client.get(f"/api/v1/life-insurance/{policy_id}", headers=admin_headers)
    assert resp.status_code == 200
    assert resp.json()["email_address"] == "customer@example.com"

    # 10. List quotes as Customer 2 (should not return Customer 1's quote)
    resp = client.get("/api/v1/life-insurance/", headers=c2_headers)
    assert resp.status_code == 200
    assert len(resp.json()) == 0

    # 11. List quotes as Customer 1 (should return Customer 1's quote)
    resp = client.get("/api/v1/life-insurance/", headers=c1_headers)
    assert resp.status_code == 200
    assert len(resp.json()) == 1
    assert resp.json()[0]["id"] == policy_id


def test_production_middleware_denies_access_without_token():
    from fastapi import FastAPI
    from app.core.middleware import JWTAuthenticationMiddleware
    
    test_app = FastAPI()
    test_app.add_middleware(JWTAuthenticationMiddleware)
    
    @test_app.get("/api/protected-route")
    def dummy_route():
        return {"ok": True}
        
    local_client = TestClient(test_app)
    resp = local_client.get("/api/protected-route")
    assert resp.status_code == 401
    assert resp.json()["detail"] == "Authentication is required. Please log in to continue."


def test_advanced_security_features(client: TestClient, db_session: Session):
    # 1. Lockout functionality test
    # Register a new user
    reg_payload = {
        "name": "Lockout User",
        "email": "lockout@example.com",
        "mobile": "1112223334",
        "role": "customer",
        "password": "Lockout@Password123"
    }
    resp = client.post("/api/auth/register", json=reg_payload)
    assert resp.status_code == 201

    # Attempt 5 failed logins
    for _ in range(5):
        resp = client.post("/api/auth/login", json={
            "email": "lockout@example.com",
            "password": "WrongPassword@123"
        })
        assert resp.status_code == 401
        assert "Incorrect credentials" in resp.json()["detail"]

    # The 6th attempt should result in a lockout
    resp = client.post("/api/auth/login", json={
        "email": "lockout@example.com",
        "password": "WrongPassword@123"
    })
    assert resp.status_code == 401
    assert "temporarily locked" in resp.json()["detail"]

    # Even correct password should be rejected during lockout
    resp = client.post("/api/auth/login", json={
        "email": "lockout@example.com",
        "password": "Lockout@Password123"
    })
    assert resp.status_code == 401
    assert "temporarily locked" in resp.json()["detail"]

    # 2. Token refresh rotation test
    reg_payload_rotate = {
        "name": "Rotate User",
        "email": "rotate@example.com",
        "mobile": "4445556667",
        "role": "customer",
        "password": "Rotate@Password123"
    }
    resp = client.post("/api/auth/register", json=reg_payload_rotate)
    assert resp.status_code == 201
    reg_data = resp.json()
    first_refresh_token = reg_data["refresh_token"]

    # Rotate token
    resp = client.post("/api/auth/refresh-token", json={"refresh_token": first_refresh_token})
    assert resp.status_code == 200
    rotate_data = resp.json()
    second_refresh_token = rotate_data["refresh_token"]
    assert second_refresh_token != first_refresh_token

    # Reusing the first refresh token should be rejected (revocation)
    resp = client.post("/api/auth/refresh-token", json={"refresh_token": first_refresh_token})
    assert resp.status_code == 401
    assert "invalid, expired, or has been revoked" in resp.json()["detail"]

    # 3. Active token invalidation (password reset) test
    reg_payload_reset = {
        "name": "Reset User",
        "email": "reset@example.com",
        "mobile": "7778889990",
        "role": "customer",
        "password": "Reset@Password123"
    }
    resp = client.post("/api/auth/register", json=reg_payload_reset)
    assert resp.status_code == 201
    reset_user_tokens = resp.json()
    access_token = reset_user_tokens["access_token"]

    # Forgot password
    resp = client.post("/api/auth/forgot-password", json={"email": "reset@example.com"})
    assert resp.status_code == 200

    # Retrieve reset token using a hack or decode from console print (let's query verification token or just use jwt if secret is known)
    # The forgot password logic prints the token. We can also generate the token manually since we know the secret and payload
    import jwt
    import os
    from datetime import datetime, timezone, timedelta
    from app.models.user import User
    user_db = db_session.exec(select(User).where(User.email == "reset@example.com")).first()
    
    JWT_SECRET = os.getenv("JWT_SECRET", "super_secret_insurance_border_key")
    token_data = {
        "sub": str(user_db.id),
        "email": user_db.email,
        "type": "reset",
        "exp": datetime.now(timezone.utc) + timedelta(minutes=15)
    }
    reset_token = jwt.encode(token_data, JWT_SECRET, algorithm="HS256")

    # Reset password
    resp = client.post("/api/auth/reset-password", json={
        "token": reset_token,
        "new_password": "NewReset@Password123"
    })
    assert resp.status_code == 200

    # Accessing protected route using the old access token should be denied
    # (since the token iat is older than the password_changed_at)
    resp = client.get("/api/auth/me", headers={"Authorization": f"Bearer {access_token}"})
    assert resp.status_code == 401
    assert resp.json()["detail"] == "Authentication is required. Please log in to continue."

    # 4. Audit Log verification
    from app.models.security_models import AuditLog
    logs = db_session.exec(select(AuditLog)).all()
    assert len(logs) > 0
    actions = [log.action for log in logs]
    assert "REGISTER" in actions
    assert "LOGIN" in actions
    assert "TOKEN_REFRESH" in actions
    assert "RESET_PASSWORD" in actions


def test_token_validation_edge_cases(client: TestClient):
    # 1. Invalid token format
    resp = client.get("/api/auth/me", headers={"Authorization": "Bearer invalidheader.invalidpayload.invalidsignature"})
    assert resp.status_code == 401
    assert resp.json()["detail"] == "Authentication is required. Please log in to continue."

    # 2. Expired token
    import jwt
    import os
    from datetime import datetime, timezone, timedelta
    JWT_SECRET = os.getenv("JWT_SECRET", "super_secret_insurance_border_key")
    expired_payload = {
        "sub": "1",
        "role": "customer",
        "email": "customer@example.com",
        "type": "access",
        "iat": (datetime.now(timezone.utc) - timedelta(hours=2)).timestamp(),
        "exp": (datetime.now(timezone.utc) - timedelta(hours=1)).timestamp()
    }
    expired_token = jwt.encode(expired_payload, JWT_SECRET, algorithm="HS256")
    resp = client.get("/api/auth/me", headers={"Authorization": f"Bearer {expired_token}"})
    assert resp.status_code == 401
    assert resp.json()["detail"] == "Authentication is required. Please log in to continue."

    # 3. Refresh token passed as access token
    refresh_payload = {
        "sub": "1",
        "role": "customer",
        "email": "customer@example.com",
        "type": "refresh",
        "iat": datetime.now(timezone.utc).timestamp(),
        "exp": (datetime.now(timezone.utc) + timedelta(hours=1)).timestamp()
    }
    refresh_as_access_token = jwt.encode(refresh_payload, JWT_SECRET, algorithm="HS256")
    resp = client.get("/api/auth/me", headers={"Authorization": f"Bearer {refresh_as_access_token}"})
    assert resp.status_code == 401
    assert resp.json()["detail"] == "Authentication is required. Please log in to continue."
