using MediatR;
using Microsoft.EntityFrameworkCore;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Application.Contracts.Dtos;

namespace SolutionErp.Application.Contracts;

// Read-only query — list changelog của 1 HĐ ordered descending CreatedAt
// (mới nhất trên cùng). Append-only table → không có Update/Delete handler.
public record ListContractChangelogsQuery(Guid ContractId, int Take = 200) : IRequest<List<ContractChangelogDto>>;

public class ListContractChangelogsQueryHandler(IApplicationDbContext db) : IRequestHandler<ListContractChangelogsQuery, List<ContractChangelogDto>>
{
    public async Task<List<ContractChangelogDto>> Handle(ListContractChangelogsQuery request, CancellationToken ct)
    {
        return await db.ContractChangelogs.AsNoTracking()
            .Where(c => c.ContractId == request.ContractId)
            .OrderByDescending(c => c.CreatedAt)
            .Take(request.Take)
            .Select(c => new ContractChangelogDto(
                c.Id, c.EntityType, c.EntityId, c.Action, c.PhaseAtChange,
                c.UserId, c.UserName, c.Summary, c.FieldChangesJson, c.ContextNote,
                c.CreatedAt))
            .ToListAsync(ct);
    }
}
