using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 创建租户账单处理器。
/// </summary>
public sealed class CreateTenantBillingCommandHandler(ITenantBillingRepository billingRepository)
    : IRequestHandler<CreateTenantBillingCommand, TenantBillingDto>
{
    /// <summary>
    /// 处理创建租户账单请求。
    /// </summary>
    /// <param name="request">创建命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>账单 DTO。</returns>
    public async Task<TenantBillingDto> Handle(CreateTenantBillingCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验账单编号
        if (string.IsNullOrWhiteSpace(request.StatementNo))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "账单编号不能为空");
        }

        // 2. 构建账单实体
        var bill = new TenantBillingStatement
        {
            TenantId = request.TenantId,
            StatementNo = request.StatementNo.Trim(),
            PeriodStart = request.PeriodStart,
            PeriodEnd = request.PeriodEnd,
            AmountDue = request.AmountDue,
            AmountPaid = request.AmountPaid,
            Status = request.Status,
            DueDate = request.DueDate,
            LineItemsJson = request.LineItemsJson
        };

        // 3. 持久化账单
        await billingRepository.AddAsync(bill, cancellationToken);
        await billingRepository.SaveChangesAsync(cancellationToken);

        // 4. 返回 DTO
        return bill.ToDto();
    }
}
