using Application.Abstractions.Data;
using Domain.Entities.Stocks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SharedKernel;
namespace Infrastructure.StockData;
///
/// 채권지수 일별시세 수집 — KRX OpenAPI (idx/bon_dd_trd, AUTH_KEY 헤더).
/// 응답 shape(총수익·순가격·재투자·시장가격 지수 + 듀레이션·컨벡시티·YTM)이 주식/파생 지수와 달라 IndexPriceSyncService 와 분리한다.
/// 기본 18:35 KST 실행(지수 수집 18:30 뒤), basDd=직전 영업일 1개 엔드포인트 전량 수집 → BondIndexDailyPrice upsert (UQ = GroupName+TradeDate).
/// 미반영(0건)이면 2시간 간격 2회 재시도. ApiKey 미설정 시 로그만 남기고 skip (다른 KRX 배치와 동일 정책).
///
internal sealed class BondIndexPriceSyncService(
IServiceScopeFactory scopeFactory,
IHttpClientFactory httpClientFactory,
IOptions settings,
ILogger logger
) : DailyScheduledService(logger)
{
private const string EndpointPath = "/svc/apis/idx/bon_dd_trd";
protected override string JobName => "BondIndexPriceSync";
protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.BondIndexSyncTime, new TimeOnly(18, 35));
protected override int MaxRetryCount => 2;
protected override TimeSpan RetryDelay => TimeSpan.FromHours(2);
protected override async Task RunOnceAsync(DateOnly todayKst, CancellationToken ct)
{
var cfg = settings.Value.KRXCoKr;
if (string.IsNullOrWhiteSpace(cfg.ApiKey))
{
Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName);
return true;
}
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName);
var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct);
var url = $"{cfg.BaseUrl.TrimEnd('/')}{EndpointPath}?basDd={targetDate:yyyyMMdd}";
var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, cfg.ApiKey, Logger, ct);
var rows = KrxBondIndexParser.ParseBondIndexPrices(json);
Logger.LogInformation("[{Job}] basDd={TargetDate} rows={Rows}", JobName, targetDate, rows.Count);
if (rows.Count == 0)
{
Logger.LogInformation("[{Job}] basDd={TargetDate} 채권지수 미반영 (0건)", JobName, targetDate);
return false;
}
var existing = await db.BondIndexDailyPrice.Where(c => c.TradeDate == targetDate).ToListAsync(ct);
var existingByKey = existing.ToDictionary(c => c.GroupName);
var inserted = 0;
var updated = 0;
foreach (var row in rows)
{
if (existingByKey.TryGetValue(row.GroupName, out var price))
{
price.Update(row.TotalEarningIndex, row.TotalEarningChange, row.NetPriceIndex, row.NetPriceChange, row.ZeroReinvestIndex, row.ZeroReinvestChange, row.CallReinvestIndex, row.CallReinvestChange, row.MarketPriceIndex, row.MarketPriceChange, row.AvgDuration, row.AvgConvexity, row.AvgYield);
updated++;
}
else
{
var created = BondIndexDailyPrice.Create(row.GroupName, row.TradeDate, row.TotalEarningIndex, row.TotalEarningChange, row.NetPriceIndex, row.NetPriceChange, row.ZeroReinvestIndex, row.ZeroReinvestChange, row.CallReinvestIndex, row.CallReinvestChange, row.MarketPriceIndex, row.MarketPriceChange, row.AvgDuration, row.AvgConvexity, row.AvgYield);
await db.BondIndexDailyPrice.AddAsync(created, ct);
existingByKey[row.GroupName] = created;
inserted++;
}
}
await db.SaveChangesAsync(ct);
Logger.LogInformation("[{Job}] 완료 — basDd={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}",
JobName, targetDate, rows.Count, inserted, updated);
return true;
}
}