import uuid
from sqlalchemy.ext.asyncio import AsyncSession
from core.exceptions import InsufficientFundsError, ValidationError
from modules.billing.models import Wallet, WalletTransaction
from modules.billing.repository import BillingRepository


class WalletService:
    """Manages prepaid tenant wallets and the immutable transaction ledger."""

    def __init__(self, db: AsyncSession):
        self.db = db
        self.repo = BillingRepository(db)

    async def get_or_create_wallet(self, tenant_id: uuid.UUID) -> Wallet:
        return await self.repo.get_or_create_wallet(tenant_id)

    async def credit(
        self,
        tenant_id: uuid.UUID,
        amount: int,
        reference_type: str,
        description: str,
        reference_id: str | None = None,
    ) -> WalletTransaction:
        if amount <= 0:
            raise ValidationError("Credit amount must be greater than zero")

        wallet = await self.get_or_create_wallet(tenant_id)
        new_balance = wallet.balance + amount
        return await self.repo.record_wallet_transaction(
            tenant_id=tenant_id,
            wallet=wallet,
            transaction_type="credit",
            amount=amount,
            balance_after=new_balance,
            reference_type=reference_type,
            reference_id=reference_id,
            description=description,
        )

    async def debit(
        self,
        tenant_id: uuid.UUID,
        amount: int,
        reference_type: str,
        description: str,
        reference_id: str | None = None,
    ) -> WalletTransaction:
        if amount <= 0:
            raise ValidationError("Debit amount must be greater than zero")

        wallet = await self.get_or_create_wallet(tenant_id)
        if wallet.is_frozen:
            raise ValidationError("Wallet is currently frozen. Contact support.")
        if wallet.balance < amount:
            raise InsufficientFundsError(
                f"Insufficient wallet balance. Required: {amount / 100:.2f}, Available: {wallet.balance / 100:.2f}"
            )

        new_balance = wallet.balance - amount
        return await self.repo.record_wallet_transaction(
            tenant_id=tenant_id,
            wallet=wallet,
            transaction_type="debit",
            amount=amount,
            balance_after=new_balance,
            reference_type=reference_type,
            reference_id=reference_id,
            description=description,
        )

    async def get_transactions(self, tenant_id: uuid.UUID) -> list[WalletTransaction]:
        wallet = await self.get_or_create_wallet(tenant_id)
        return await self.repo.get_wallet_transactions(wallet.id)
