// EN: Attendance record aggregate — tracks daily check-in/check-out for staff.
// VI: Aggregate cham cong — theo doi check-in/check-out hang ngay cua nhan vien.

using MerchantService.Domain.SeedWork;

namespace MerchantService.Domain.AggregatesModel.AttendanceAggregate;

/// <summary>
/// EN: Daily attendance record for a staff member.
/// VI: Ban ghi cham cong hang ngay cho nhan vien.
/// </summary>
public class AttendanceRecord : Entity, IAggregateRoot
{
    private Guid _staffId;
    private Guid _shopId;
    private DateTime _date;
    private DateTime? _checkIn;
    private DateTime? _checkOut;
    private decimal? _hoursWorked;
    private string _status; // Working, Completed, Late, Absent
    private string? _notes;
    private DateTime _createdAt;
    private DateTime? _updatedAt;

    public Guid StaffId => _staffId;
    public Guid ShopId => _shopId;
    public DateTime Date => _date;
    public DateTime? CheckIn => _checkIn;
    public DateTime? CheckOut => _checkOut;
    public decimal? HoursWorked => _hoursWorked;
    public string Status => _status;
    public string? Notes => _notes;
    public DateTime CreatedAt => _createdAt;

    protected AttendanceRecord() { _status = "Working"; }

    /// <summary>
    /// EN: Create attendance record with check-in.
    /// VI: Tao ban ghi cham cong voi check-in.
    /// </summary>
    public static AttendanceRecord CheckInNow(Guid staffId, Guid shopId)
    {
        var now = DateTime.UtcNow;
        var record = new AttendanceRecord
        {
            Id = Guid.NewGuid(),
            _staffId = staffId,
            _shopId = shopId,
            _date = now.Date,
            _checkIn = now,
            _status = "Working",
            _createdAt = now
        };
        return record;
    }

    /// <summary>
    /// EN: Record check-out and calculate hours worked.
    /// VI: Ghi nhan check-out va tinh gio lam.
    /// </summary>
    public void DoCheckOut()
    {
        if (_checkOut.HasValue)
            throw new InvalidOperationException("Already checked out / Da check-out roi");

        _checkOut = DateTime.UtcNow;
        if (_checkIn.HasValue)
            _hoursWorked = (decimal)(_checkOut.Value - _checkIn.Value).TotalHours;
        _status = "Completed";
        _updatedAt = DateTime.UtcNow;
    }

    /// <summary>
    /// EN: Mark as absent (admin action).
    /// VI: Danh dau vang mat (thao tac admin).
    /// </summary>
    public void MarkAbsent(string? notes = null)
    {
        _status = "Absent";
        _notes = notes;
        _updatedAt = DateTime.UtcNow;
    }

    /// <summary>
    /// EN: Mark as late.
    /// VI: Danh dau di muon.
    /// </summary>
    public void MarkLate()
    {
        _status = "Late";
        _updatedAt = DateTime.UtcNow;
    }
}
