// EN: Check-in command for staff attendance.
// VI: Command cham cong vao cho nhan vien.

using MediatR;
using MerchantService.Domain.AggregatesModel.AttendanceAggregate;

namespace MerchantService.API.Application.Commands.Attendance;

public record CheckInCommand(Guid StaffId, Guid ShopId) : IRequest<CheckInResult>;
public record CheckInResult(Guid AttendanceId, DateTime CheckIn);

public class CheckInCommandHandler : IRequestHandler<CheckInCommand, CheckInResult>
{
    private readonly IAttendanceRepository _repo;
    private readonly ILogger<CheckInCommandHandler> _logger;

    public CheckInCommandHandler(IAttendanceRepository repo, ILogger<CheckInCommandHandler> logger)
    {
        _repo = repo;
        _logger = logger;
    }

    public async Task<CheckInResult> Handle(CheckInCommand request, CancellationToken ct)
    {
        var existing = await _repo.GetTodayRecordAsync(request.StaffId, ct);
        if (existing != null)
            return new CheckInResult(existing.Id, existing.CheckIn ?? DateTime.UtcNow);

        var record = AttendanceRecord.CheckInNow(request.StaffId, request.ShopId);
        _repo.Add(record);
        await _repo.UnitOfWork.SaveEntitiesAsync(ct);

        _logger.LogInformation("EN: Staff checked in / VI: Nhan vien da check-in: StaffId={StaffId}", request.StaffId);
        return new CheckInResult(record.Id, record.CheckIn ?? DateTime.UtcNow);
    }
}
