from django.db import transaction
from django.utils import timezone
from .accounting import JournalService,LedgerPostingService,AssetAccountingService
from .models import FixedAssetBook,JournalEntry
from .constants import GLCode


@transaction.atomic
def repair_starter_stadium(purchase):
    """Add a correcting journal and missing historical cost; never edit a ledger."""
    from clubs.models import Club
    Club.objects.select_for_update().get(pk=purchase.club_id)
    original=LedgerPostingService.post_entry(club=purchase.club,entry=purchase.ledger_entry)
    if original is None:return False
    if not original.lines.filter(account__code=GLCode.OTHER_NFT_ASSETS,debit__gt=0).exists():
        AssetAccountingService.after_cash_ledger_posted(club=purchase.club,entry=purchase.ledger_entry,journal=original)
        return False
    key=f'gl-starter-correction:{purchase.pk}'
    if JournalEntry.objects.filter(idempotency_key=key).exists():return False
    amount=purchase.ledger_entry.amount
    JournalService.post(club=purchase.club,accounting_date=timezone.localdate(),source_type='STARTER_STADIUM_CORRECTION',source_id=str(purchase.pk),
        idempotency_key=key,memo='Reclassify historical starter stadium to depreciable facilities',lines=[
            {'account':GLCode.CLUB_FACILITIES,'debit':amount,'credit':0},
            {'account':GLCode.OTHER_NFT_ASSETS,'debit':0,'credit':amount}])
    book=FixedAssetBook.objects.filter(club=purchase.club,asset=purchase.stadium,disposed_on__isnull=True).first()
    if book:
        book.acquisition_cost+=amount; book.save(update_fields=['acquisition_cost','updated_at'])
    else:
        FixedAssetBook.objects.create(club=purchase.club,asset=purchase.stadium,acquisition_cost=amount,residual_value=0,useful_life_months=240,
            placed_in_service=purchase.created_at.date(),source_type='STARTER_STADIUM',source_id=str(purchase.pk))
    return True
