from datetime import date
from decimal import Decimal

from app.core.security import get_password_hash
from app.models.customer import Customer
from app.models.enums import PolicyStatus, UserRole
from app.models.policy import Policy
from app.models.user import User


def _create_policy(db, agency_id: int, customer_id: int, created_by: int, policy_number: str) -> Policy:
    policy = Policy(
        agency_id=agency_id,
        customer_id=customer_id,
        policy_number=policy_number,
        policy_end_date=date(2027, 1, 1),
        status=PolicyStatus.ACTIVE,
        total_commission=Decimal("100.00"),
        total_paid=Decimal("0.00"),
        pending_amount=Decimal("100.00"),
        created_by=created_by,
    )
    db.add(policy)
    db.commit()
    db.refresh(policy)
    return policy


def test_agent_can_delete_own_policy(client, db, seed_data):
    agency = seed_data["agency"]
    agent = User(
        agency_id=agency.id,
        email="delete-agent@test.com",
        full_name="Delete Agent",
        hashed_password=get_password_hash("Agent@12345"),
        role=UserRole.AGENT,
        is_active=True,
    )
    other_agent = User(
        agency_id=agency.id,
        email="other-agent@test.com",
        full_name="Other Agent",
        hashed_password=get_password_hash("Agent@12345"),
        role=UserRole.AGENT,
        is_active=True,
    )
    db.add_all([agent, other_agent])
    db.commit()

    customer = Customer(agency_id=agency.id, name="Test Customer", mobile="9999900001")
    db.add(customer)
    db.commit()

    own_policy = _create_policy(db, agency.id, customer.id, agent.id, "OWN-POL-001")
    other_policy = _create_policy(db, agency.id, customer.id, other_agent.id, "OTHER-POL-001")

    login = client.post("/api/v1/auth/login", json={"email": "delete-agent@test.com", "password": "Agent@12345"})
    headers = {"Authorization": f"Bearer {login.json()['access_token']}"}

    detail = client.get(f"/api/v1/policies/{own_policy.id}", headers=headers)
    assert detail.status_code == 200
    assert detail.json()["can_delete"] is True

    denied = client.delete(f"/api/v1/policies/{other_policy.id}", headers=headers)
    assert denied.status_code == 403

    ok = client.delete(f"/api/v1/policies/{own_policy.id}", headers=headers)
    assert ok.status_code == 200


def test_admin_can_delete_any_policy(client, auth_headers, db, seed_data):
    agency = seed_data["agency"]
    admin = seed_data["admin"]
    customer = Customer(agency_id=agency.id, name="Admin Customer", mobile="9999900002")
    db.add(customer)
    db.commit()

    policy = _create_policy(db, agency.id, customer.id, admin.id, "ADMIN-DEL-001")

    ok = client.delete(f"/api/v1/policies/{policy.id}", headers=auth_headers)
    assert ok.status_code == 200
