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

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

namespace MerchantService.API.Application.Commands.Attendance;

public record CheckOutCommand(Guid StaffId) : IRequest<CheckOutResult>;
public record CheckOutResult(Guid AttendanceId, DateTime CheckOut, decimal HoursWorked);

public class CheckOutCommandHandler : IRequestHandler<CheckOutCommand, CheckOutResult>
{
    private readonly IAttendanceRepository _repo;
    private readonly ILogger<CheckOutCommandHandler> _logger;

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

    public async Task<CheckOutResult> Handle(CheckOutCommand request, CancellationToken ct)
    {
        var record = await _repo.GetTodayRecordAsync(request.StaffId, ct)
            ?? throw new InvalidOperationException("No check-in record found for today / Chua check-in hom nay");

        record.DoCheckOut();
        _repo.Update(record);
        await _repo.UnitOfWork.SaveEntitiesAsync(ct);

        _logger.LogInformation("EN: Staff checked out / VI: Nhan vien da check-out: StaffId={StaffId}, Hours={Hours}",
            request.StaffId, record.HoursWorked);
        return new CheckOutResult(record.Id, record.CheckOut ?? DateTime.UtcNow, record.HoursWorked ?? 0);
    }
}
