"""Attendance & Access Control APIs — Phase 9.5."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination, require_tenant
from app.core.security import get_current_user
from app.schemas.attendance import (
    AccessLogRead,
    AttendanceRecordCreate,
    AttendanceRecordRead,
    CheckInRequest,
    CheckOutRequest,
)
from app.services.attendance import AttendanceService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

attendance_router = APIRouter()
access_logs_router = APIRouter()
check_in_router = APIRouter()
check_out_router = APIRouter()


@check_in_router.post("", response_model=AttendanceRecordRead, status_code=status.HTTP_201_CREATED)
async def check_in(body: CheckInRequest, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db), user: CurrentUser = Depends(get_current_user)):
    return await AttendanceService(db).check_in(tenant_id, body, actor=user)


@check_out_router.post("", response_model=AttendanceRecordRead, status_code=status.HTTP_201_CREATED)
async def check_out(body: CheckOutRequest, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db), user: CurrentUser = Depends(get_current_user)):
    return await AttendanceService(db).check_out(tenant_id, body, actor=user)


@attendance_router.post("", response_model=AttendanceRecordRead, status_code=status.HTTP_201_CREATED)
async def create_manual_attendance(body: AttendanceRecordCreate, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db), user: CurrentUser = Depends(get_current_user)):
    return await AttendanceService(db).create_manual(tenant_id, body, actor=user)


@attendance_router.get("", response_model=list[AttendanceRecordRead])
async def list_attendance(member_id: UUID = Query(...), tenant_id: UUID = Depends(require_tenant), pagination: PaginationParams = Depends(get_pagination), db: AsyncSession = Depends(get_db), _user: CurrentUser = Depends(get_current_user)):
    return await AttendanceService(db).list_records(tenant_id, member_id, offset=pagination.offset, limit=pagination.page_size)


@access_logs_router.get("", response_model=list[AccessLogRead])
async def list_access_logs(member_id: UUID = Query(...), tenant_id: UUID = Depends(require_tenant), pagination: PaginationParams = Depends(get_pagination), db: AsyncSession = Depends(get_db), _user: CurrentUser = Depends(get_current_user)):
    return await AttendanceService(db).list_access_logs(tenant_id, member_id, offset=pagination.offset, limit=pagination.page_size)
