using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 更新排班处理器。
/// </summary>
public sealed class UpdateStoreEmployeeShiftCommandHandler(
    IStoreRepository storeRepository,
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStoreEmployeeShiftCommandHandler> logger)
    : IRequestHandler<UpdateStoreEmployeeShiftCommand, StoreEmployeeShiftDto?>
{
    /// <inheritdoc />
    public async Task<StoreEmployeeShiftDto?> Handle(UpdateStoreEmployeeShiftCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取排班
        var tenantId = tenantProvider.GetCurrentTenantId();
        var shift = await storeRepository.FindShiftByIdAsync(request.ShiftId, tenantId, cancellationToken);
        if (shift is null)
        {
            return null;
        }

        // 2. 校验门店归属
        if (shift.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "排班不属于该门店");
        }

        // 3. 校验员工归属
        var staff = await merchantRepository.FindStaffByIdAsync(request.StaffId, tenantId, cancellationToken);
        if (staff is null || (staff.StoreId.HasValue && staff.StoreId != request.StoreId))
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "员工不存在或不属于该门店");
        }

        // 4. 冲突校验
        var shifts = await storeRepository.GetShiftsAsync(request.StoreId, tenantId, request.ShiftDate.Date, request.ShiftDate.Date, cancellationToken);
        var hasConflict = shifts.Any(x => x.Id != request.ShiftId && x.StaffId == request.StaffId && x.ShiftDate == request.ShiftDate);
        if (hasConflict)
        {
            throw new BusinessException(ErrorCodes.Conflict, "该员工当日已存在排班");
        }

        // 5. 更新字段
        shift.StaffId = request.StaffId;
        shift.ShiftDate = request.ShiftDate.Date;
        shift.StartTime = request.StartTime;
        shift.EndTime = request.EndTime;
        shift.RoleType = request.RoleType;
        shift.Notes = request.Notes?.Trim();

        // 6. 持久化
        await storeRepository.UpdateShiftAsync(shift, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新排班 {ShiftId} 员工 {StaffId} 门店 {StoreId}", shift.Id, shift.StaffId, shift.StoreId);

        // 7. 返回 DTO
        return StoreMapping.ToDto(shift);
    }
}
