using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Microsoft.EntityFrameworkCore;
namespace Application.Features.Api.Stocks.GetSriBonds;
///
/// 사회책임투자채권 목록 — 지정일(미지정 시 최신 TradeDate) 스냅샷을 발행금액 내림차순으로 페이징 (KRX 사회책임투자채권 수집, 익명).
/// BondType(SRI_BND_TP_NM 채권종류) 지정 시 해당 종류만 필터한다.
///
internal sealed class Handler(IAppDbContext db) : IQueryHandler
{
private const ushort MaxPerPage = 100;
public async Task Handle(Query request, CancellationToken ct)
{
var page = request.Page < 1 ? 1 : request.Page;
var perPage = request.PerPage is 0 or > MaxPerPage ? (ushort)20 : request.PerPage;
var targetDate = request.Date;
if (targetDate is null)
{
targetDate = await db.SriBond.AsNoTracking()
.OrderByDescending(c => c.TradeDate)
.Select(c => (DateOnly?)c.TradeDate)
.FirstOrDefaultAsync(ct);
}
if (targetDate is null)
{
return new Response
{
Total = 0,
TradeDate = null,
List = []
};
}
var query = db.SriBond.AsNoTracking().Where(c => c.TradeDate == targetDate.Value);
if (!string.IsNullOrWhiteSpace(request.BondType))
{
var bondType = request.BondType.Trim();
query = query.Where(c => c.SriBondType == bondType);
}
var total = await query.CountAsync(ct);
var list = await query
.OrderByDescending(c => c.IssueAmount).ThenBy(c => c.Code)
.Skip((page - 1) * perPage)
.Take(perPage)
.Select(c => new Response.Row
{
Code = c.Code,
IssuerName = c.IssuerName,
SriBondType = c.SriBondType,
Name = c.Name,
ListDate = c.ListDate,
IssueDate = c.IssueDate,
RedemptionDate = c.RedemptionDate,
CouponRate = c.CouponRate,
IssueAmount = c.IssueAmount,
ListAmount = c.ListAmount,
BondType = c.BondType
})
.ToListAsync(ct);
return new Response
{
Total = total,
TradeDate = targetDate.Value,
List = list
};
}
}