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

namespace TakeoutSaaS.Application.App.Billings.Handlers;

/// <summary>
/// 创建账单处理器。
/// </summary>
public sealed class CreateBillCommandHandler(
    ITenantBillingRepository billingRepository,
    ITenantRepository tenantRepository,
    IIdGenerator idGenerator)
    : IRequestHandler<CreateBillCommand, BillDto>
{
    /// <summary>
    /// 处理创建账单请求。
    /// </summary>
    /// <param name="request">创建命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>账单 DTO。</returns>
    public async Task<BillDto> Handle(CreateBillCommand request, CancellationToken cancellationToken)
    {
        // 1. 验证租户存在
        var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken);
        if (tenant is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
        }

        // 2. 生成账单编号
        var statementNo = $"BILL-{DateTime.UtcNow:yyyyMMdd}-{idGenerator.NextId()}";

        // 3. 构建账单实体
        var bill = new TenantBillingStatement
        {
            TenantId = request.TenantId,
            StatementNo = statementNo,
            PeriodStart = DateTime.UtcNow,
            PeriodEnd = DateTime.UtcNow,
            AmountDue = request.AmountDue,
            AmountPaid = 0,
            Status = TenantBillingStatus.Pending,
            DueDate = request.DueDate,
            LineItemsJson = request.Notes
        };

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

        // 5. 返回 DTO
        return bill.ToDto(tenant.Name);
    }
}
