"""Attendance repositories — Phase 9.5."""
from __future__ import annotations

from datetime import datetime
from uuid import UUID

from sqlalchemy import select

from app.models.attendance import AccessLog, AttendanceRecord
from app.repositories.base import TenantBaseRepository


class AttendanceRecordRepository(TenantBaseRepository[AttendanceRecord]):
    model = AttendanceRecord

    async def list_by_member(
        self, tenant_id: UUID, member_id: UUID, *, offset: int = 0, limit: int = 20
    ):
        stmt = (
            select(self.model)
            .where(
                self.model.tenant_id == tenant_id,
                self.model.member_id == member_id,
                self.model.is_deleted.is_(False),
            )
            .order_by(self.model.recorded_at.desc())
            .offset(offset)
            .limit(limit)
        )
        result = await self.session.execute(stmt)
        return result.scalars().all()

    async def latest_for_member(
        self, tenant_id: UUID, member_id: UUID, *, before: datetime | None = None
    ):
        clauses = [
            self.model.tenant_id == tenant_id,
            self.model.member_id == member_id,
            self.model.is_deleted.is_(False),
        ]
        if before:
            clauses.append(self.model.recorded_at <= before)
        stmt = select(self.model).where(*clauses).order_by(self.model.recorded_at.desc()).limit(1)
        return (await self.session.execute(stmt)).scalar_one_or_none()


class AccessLogRepository(TenantBaseRepository[AccessLog]):
    model = AccessLog

    async def list_by_member(
        self, tenant_id: UUID, member_id: UUID, *, offset: int = 0, limit: int = 20
    ):
        stmt = (
            select(self.model)
            .where(
                self.model.tenant_id == tenant_id,
                self.model.member_id == member_id,
                self.model.is_deleted.is_(False),
            )
            .order_by(self.model.recorded_at.desc())
            .offset(offset)
            .limit(limit)
        )
        result = await self.session.execute(stmt)
        return result.scalars().all()
