"""Ledger repositories."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select

from app.models.ledger import (
    GeneralLedger,
    LedgerBalance,
    TrialBalanceSnapshot,
)
from app.repositories.base import TenantBaseRepository


class GeneralLedgerRepository(TenantBaseRepository[GeneralLedger]):
    model = GeneralLedger

    async def list_by_account_period(
        self, tenant_id: UUID, account_id: UUID, fiscal_period_id: UUID
    ):
        stmt = (
            select(GeneralLedger)
            .where(
                GeneralLedger.tenant_id == tenant_id,
                GeneralLedger.account_id == account_id,
                GeneralLedger.fiscal_period_id == fiscal_period_id,
            )
            .order_by(GeneralLedger.entry_date)
        )
        result = await self.session.execute(stmt)
        return result.scalars().all()


class LedgerBalanceRepository(TenantBaseRepository[LedgerBalance]):
    model = LedgerBalance

    async def get_by_account_period(
        self, tenant_id: UUID, account_id: UUID, fiscal_period_id: UUID
    ) -> LedgerBalance | None:
        stmt = select(LedgerBalance).where(
            LedgerBalance.tenant_id == tenant_id,
            LedgerBalance.account_id == account_id,
            LedgerBalance.fiscal_period_id == fiscal_period_id,
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()

    async def list_by_period(self, tenant_id: UUID, fiscal_period_id: UUID):
        stmt = select(LedgerBalance).where(
            LedgerBalance.tenant_id == tenant_id,
            LedgerBalance.fiscal_period_id == fiscal_period_id,
        )
        result = await self.session.execute(stmt)
        return result.scalars().all()


class TrialBalanceSnapshotRepository(TenantBaseRepository[TrialBalanceSnapshot]):
    model = TrialBalanceSnapshot
