from app.core.security import get_password_hash
from app.models.enums import UserRole
from app.models.insurance_company import InsuranceCompany
from app.models.user import User


def _super_admin_headers(client, db, seed_data):
    super_admin = User(
        agency_id=seed_data["agency"].id,
        email="super-insurers@test.com",
        full_name="Super Insurers",
        hashed_password=get_password_hash("Super@12345"),
        role=UserRole.SUPER_ADMIN,
        is_active=True,
    )
    db.add(super_admin)
    db.commit()

    login = client.post("/api/v1/auth/login", json={"email": "super-insurers@test.com", "password": "Super@12345"})
    assert login.status_code == 200
    return {"Authorization": f"Bearer {login.json()['access_token']}"}


def test_super_admin_manage_insurance_companies(client, db, seed_data):
    headers = _super_admin_headers(client, db, seed_data)

    listed = client.get("/api/v1/super-admin/insurance-companies", headers=headers)
    assert listed.status_code == 200
    initial_count = len(listed.json())

    created = client.post(
        "/api/v1/super-admin/insurance-companies",
        headers=headers,
        json={
            "name": "Test Insurer Co",
            "code": "test_insurer_co",
            "parser_key": "generic",
            "is_active": True,
        },
    )
    assert created.status_code == 200
    body = created.json()
    assert body["name"] == "Test Insurer Co"
    assert body["code"] == "test_insurer_co"
    assert body["parser_key"] == "generic"

    company_id = body["id"]
    updated = client.patch(
        f"/api/v1/super-admin/insurance-companies/{company_id}",
        headers=headers,
        json={"name": "Test Insurer Updated", "is_active": False},
    )
    assert updated.status_code == 200
    assert updated.json()["name"] == "Test Insurer Updated"
    assert updated.json()["is_active"] is False

    listed_after = client.get("/api/v1/super-admin/insurance-companies", headers=headers)
    assert listed_after.status_code == 200
    assert len(listed_after.json()) == initial_count + 1


def test_agency_admin_cannot_manage_insurance_companies(client, auth_headers, db, seed_data):
    db.add(
        InsuranceCompany(name="Seed Insurer", code="seed_insurer", parser_key="generic", is_active=True)
    )
    db.commit()

    denied = client.get("/api/v1/super-admin/insurance-companies", headers=auth_headers)
    assert denied.status_code == 403

    denied_create = client.post(
        "/api/v1/super-admin/insurance-companies",
        headers=auth_headers,
        json={"name": "Blocked", "code": "blocked", "parser_key": "generic"},
    )
    assert denied_create.status_code == 403
