using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Infrastructure.App.Persistence;

namespace TakeoutSaaS.Infrastructure.App.Repositories;

/// <summary>
/// EF 租户账单仓储。
/// </summary>
public sealed class EfTenantBillingRepository(TakeoutAppDbContext context) : ITenantBillingRepository
{
    /// <inheritdoc />
    public Task<IReadOnlyList<TenantBillingStatement>> SearchAsync(
        long tenantId,
        TenantBillingStatus? status,
        DateTime? from,
        DateTime? to,
        CancellationToken cancellationToken = default)
    {
        var query = context.TenantBillingStatements.AsNoTracking()
            .Where(x => x.TenantId == tenantId);

        if (status.HasValue)
        {
            query = query.Where(x => x.Status == status.Value);
        }

        if (from.HasValue)
        {
            query = query.Where(x => x.PeriodStart >= from.Value);
        }

        if (to.HasValue)
        {
            query = query.Where(x => x.PeriodEnd <= to.Value);
        }

        return query
            .OrderByDescending(x => x.PeriodEnd)
            .ToListAsync(cancellationToken)
            .ContinueWith(t => (IReadOnlyList<TenantBillingStatement>)t.Result, cancellationToken);
    }

    /// <inheritdoc />
    public Task<TenantBillingStatement?> FindByIdAsync(long tenantId, long billingId, CancellationToken cancellationToken = default)
    {
        return context.TenantBillingStatements.AsNoTracking()
            .FirstOrDefaultAsync(x => x.TenantId == tenantId && x.Id == billingId, cancellationToken);
    }

    /// <inheritdoc />
    public Task<TenantBillingStatement?> FindByStatementNoAsync(long tenantId, string statementNo, CancellationToken cancellationToken = default)
    {
        return context.TenantBillingStatements.AsNoTracking()
            .FirstOrDefaultAsync(x => x.TenantId == tenantId && x.StatementNo == statementNo, cancellationToken);
    }

    /// <inheritdoc />
    public Task AddAsync(TenantBillingStatement bill, CancellationToken cancellationToken = default)
    {
        return context.TenantBillingStatements.AddAsync(bill, cancellationToken).AsTask();
    }

    /// <inheritdoc />
    public Task UpdateAsync(TenantBillingStatement bill, CancellationToken cancellationToken = default)
    {
        context.TenantBillingStatements.Update(bill);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        return context.SaveChangesAsync(cancellationToken);
    }
}
