"""Phase 6 marketplace audit fixes.

Coverage:
* ``close_expired_demand_listings`` flips OPEN listings past their
  ``deadline`` to CLOSED and notifies the buyer-managing user.
* Already-CLOSED listings are skipped (idempotency).
* Listings without a deadline are not auto-closed.
"""
from __future__ import annotations

from datetime import timedelta

import pytest
from django.contrib.auth import get_user_model
from django.utils import timezone

from apps.core.permissions.roles import UserRole
from apps.smehub.marketplace import services
from apps.smehub.marketplace.models import BuyerRegistryEntry, MarketDemandListing

User = get_user_model()
pytestmark = pytest.mark.django_db


@pytest.fixture
def admin():
    return User.objects.create_user(
        email="adm-mp6@example.com", password="x",
        is_superuser=True, is_staff=True, role=UserRole.SYSTEM_ADMIN,
    )


@pytest.fixture
def buyer_user():
    return User.objects.create_user(
        email="buyer-mp6@example.com", password="x", role=UserRole.BUYER,
    )


@pytest.fixture
def verified_buyer(admin, buyer_user):
    entry = BuyerRegistryEntry.objects.create(
        user=buyer_user,
        organisation_name="MP6 Buyer",
        org_type=BuyerRegistryEntry.OrgType.INSTITUTIONAL,
    )
    entry.verify(by_user=admin)
    entry.save()
    return entry


def _make_listing(buyer, *, deadline) -> MarketDemandListing:
    return MarketDemandListing.objects.create(
        buyer=buyer,
        title="MP6 listing",
        description="x",
        deadline=deadline,
    )


def test_close_expired_demand_listings_flips_past_deadline(verified_buyer):
    listing = _make_listing(verified_buyer, deadline=timezone.now() - timedelta(hours=1))
    count = services.close_expired_demand_listings()
    assert count == 1
    fresh = MarketDemandListing.objects.get(pk=listing.pk)
    assert fresh.status == MarketDemandListing.Status.CLOSED
    assert fresh.closed_at is not None


def test_close_expired_demand_listings_skips_future_deadline(verified_buyer):
    _make_listing(verified_buyer, deadline=timezone.now() + timedelta(days=2))
    count = services.close_expired_demand_listings()
    assert count == 0


def test_close_expired_demand_listings_skips_listings_without_deadline(verified_buyer):
    listing = _make_listing(verified_buyer, deadline=None)
    count = services.close_expired_demand_listings()
    assert count == 0
    fresh = MarketDemandListing.objects.get(pk=listing.pk)
    assert fresh.status == MarketDemandListing.Status.OPEN


def test_close_expired_demand_listings_is_idempotent(verified_buyer):
    """Already-CLOSED listings stay CLOSED and aren't re-counted."""
    _make_listing(verified_buyer, deadline=timezone.now() - timedelta(hours=1))
    services.close_expired_demand_listings()
    second = services.close_expired_demand_listings()
    assert second == 0
