"""Tests for phases 5.7–5.11."""
import uuid
from decimal import Decimal

import pytest

from app.tests.conftest import TENANT_A, tenant_headers


@pytest.mark.asyncio
async def test_create_purchase_profile(client):
    resp = await client.post(
        "/api/v1/purchase-inventory/posting-profiles",
        json={"name": "Default Purchase", "is_default": True},
        headers=tenant_headers(TENANT_A),
    )
    assert resp.status_code == 201


@pytest.mark.asyncio
async def test_create_asset_category(client):
    resp = await client.post(
        "/api/v1/assets/categories",
        json={"code": "VEH", "name": "Vehicles"},
        headers=tenant_headers(TENANT_A),
    )
    assert resp.status_code == 201


@pytest.mark.asyncio
async def test_create_asset(client):
    resp = await client.post(
        "/api/v1/assets/assets",
        json={"code": "AST-001", "name": "Office Desk", "acquisition_cost": "5000000"},
        headers=tenant_headers(TENANT_A),
    )
    assert resp.status_code == 201
    assert resp.json()["code"] == "AST-001"


@pytest.mark.asyncio
async def test_depreciation_engine():
    from app.models.fixed_assets import Asset
    from app.models.types import DepreciationMethod
    from app.services.asset_service import DepreciationEngine

    asset = Asset(
        tenant_id=uuid.uuid4(),
        code="T1",
        name="Test",
        acquisition_cost=Decimal("1200000"),
        current_book_value=Decimal("1200000"),
        residual_value=Decimal("0"),
        useful_life_months=12,
        depreciation_method=DepreciationMethod.STRAIGHT_LINE,
    )
    engine = DepreciationEngine()
    amount = engine.calculate(asset)
    assert amount == Decimal("100000.0000")
    schedule = engine.generate_schedule(asset)
    assert len(schedule) == 12


@pytest.mark.asyncio
async def test_create_employee(client):
    resp = await client.post(
        "/api/v1/payroll/employees",
        json={"employee_code": "EMP-001", "first_name": "Ali", "last_name": "Rezaei", "base_salary": "50000000"},
        headers=tenant_headers(TENANT_A),
    )
    assert resp.status_code == 201


@pytest.mark.asyncio
async def test_payroll_calculation():
    from app.models.payroll import Employee
    from app.models.types import EmploymentStatus
    from app.services.payroll_service import PayrollEngine

    employee = Employee(
        tenant_id=uuid.uuid4(),
        employee_code="E1",
        first_name="Test",
        last_name="User",
        base_salary=Decimal("10000000"),
        employment_status=EmploymentStatus.ACTIVE,
    )
    engine = PayrollEngine()
    result = engine.calculate(employee, benefits=Decimal("1000000"), deductions=Decimal("500000"))
    assert result["gross_salary"] == Decimal("11000000")
    assert result["net_salary"] == Decimal("10500000")


@pytest.mark.asyncio
async def test_generate_trial_balance_report(client):
    period_id = str(uuid.uuid4())
    resp = await client.post(
        "/api/v1/reporting/trial-balance",
        params={"fiscal_period_id": period_id},
        headers=tenant_headers(TENANT_A),
    )
    assert resp.status_code == 200
    assert "report_type" in resp.json()


@pytest.mark.asyncio
async def test_create_audit_record(client):
    resp = await client.post(
        "/api/v1/compliance/audit-records",
        json={
            "action": "voucher.posted",
            "resource_type": "voucher",
            "resource_id": str(uuid.uuid4()),
            "source_module": "accounting",
        },
        headers=tenant_headers(TENANT_A),
    )
    assert resp.status_code == 201


@pytest.mark.asyncio
async def test_inventory_valuation_engine():
    from app.services.purchase_inventory_service import InventoryValuationEngine

    engine = InventoryValuationEngine()
    avg = engine.calculate_weighted_average(Decimal("10"), Decimal("10000"), Decimal("5"), Decimal("1200"))
    assert avg == Decimal("10000") / Decimal("15") + Decimal("6000") / Decimal("15")


@pytest.mark.asyncio
async def test_tenant_isolation_assets(client):
    resp = await client.post(
        "/api/v1/assets/assets",
        json={"code": "ISO-001", "name": "Isolated Asset"},
        headers=tenant_headers(TENANT_A),
    )
    asset_id = resp.json()["id"]

    other_tenant = uuid.uuid4()
    list_resp = await client.get("/api/v1/assets/assets", headers=tenant_headers(other_tenant))
    assert list_resp.status_code == 200
    assert len(list_resp.json()) == 0
