using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Application.Common;
using SharedKernel.Results;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.MyPage.GetExpLogs;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Result<Response>>
{
    public async Task<Result<Response>> Handle(Query request, CancellationToken ct)
    {
        var page = request.Page < 1 ? 1 : request.Page;
        var perPage = request.PerPage is < 1 or > 50 ? 20 : request.PerPage;

        var now = DateTime.UtcNow;
        var startDate = request.Type switch
        {
            SearchDateType.Week => now.AddDays(-7),
            SearchDateType.Month => now.AddMonths(-1),
            SearchDateType.QuarterYear => now.AddMonths(-3),
            SearchDateType.HalfYear => now.AddMonths(-6),
            _ => now.Date
        };

        var query = db.MemberExpLog.AsNoTracking().Where(l => l.MemberID == request.MemberID && l.CreatedAt >= startDate).OrderByDescending(l => l.CreatedAt);
        var total = await query.CountAsync(ct);

        var list = await query
            .Skip((page - 1) * perPage)
            .Take(perPage)
            .Select(l => new ExpLogItem(
                l.ID,
                l.Reason,
                l.Amount,
                l.Balance,
                l.CreatedAt
            ))
            .ToListAsync(ct);

        return Result.Success(new Response(list, total, page, perPage));
    }
}