"""Auth-related use cases: check-in, complete profile."""
from __future__ import annotations

import datetime

from domain.repositories import AttendanceRepository


class CheckIn:
    """Record today's check-in (now) unless one already exists. Idempotent: calling it again the
    same day never overwrites an existing check_in. Whether a person is expected to check in is
    decided by the caller from their permissions, not here.
    """

    def __init__(self, attendance_repo: AttendanceRepository):
        self.attendance_repo = attendance_repo

    def execute(self, user) -> None:
        today = datetime.date.today()
        existing = self.attendance_repo.get_for_day(user.id, today)
        if existing is not None and existing.check_in is not None:
            return
        now = datetime.datetime.now().time().replace(microsecond=0)
        if existing is None:
            self.attendance_repo.create(user_id=user.id, date=today, check_in=now)
        else:
            existing.check_in = now
            self.attendance_repo.save(existing)


class CompleteProfile:
    """Sets the user's name for the first time (or updates it)."""

    def __init__(self, user_repo):
        self.user_repo = user_repo

    def execute(self, user, name: str):
        user.name = name.strip()
        self.user_repo.save(user)
        return user
