using Application.Abstractions.Data;
using Domain.Entities.Stocks;
using Domain.Entities.Stocks.ValueObject;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SharedKernel;
namespace Infrastructure.StockData;
///
/// 신주인수권증권/증서 일별매매 수집 (KRX OpenAPI) — sw_bydd_trd(증권) + sr_bydd_trd(증서).
/// 기본 18:25 KST 실행(장 마감 15:30 이후 확정, 증권상품 수집 18:20 뒤), basDd=직전 영업일 2개 엔드포인트 전량 수집 →
/// WarrantDailyTrade upsert (UQ = WarrantType+Code+TradeDate). 미반영(0건)이면 2시간 간격 2회 재시도.
/// 증서(sr)는 유상증자 시에만 상장되는 단기 상품이라 대부분의 영업일에 0건이 정상 — 두 엔드포인트 합계로 0 판정한다.
/// ApiKey 미설정 시 로그만 남기고 skip (다른 KRX 배치와 동일 정책).
///
internal sealed class KrxWarrantSyncService(
IServiceScopeFactory scopeFactory,
IHttpClientFactory httpClientFactory,
IOptions settings,
ILogger logger
) : DailyScheduledService(logger)
{
// (유형, 엔드포인트 경로) — 증권(sw)/증서(sr)
private static readonly (WarrantType Type, string Path)[] Endpoints =
[
(WarrantType.SubscriptionWarrant, "/svc/apis/sto/sw_bydd_trd"),
(WarrantType.SubscriptionRight, "/svc/apis/sto/sr_bydd_trd")
];
protected override string JobName => "KrxWarrantSync";
protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.WarrantSyncTime, new TimeOnly(18, 25));
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 rows = new List();
foreach (var (type, path) in Endpoints)
{
var url = $"{cfg.BaseUrl.TrimEnd('/')}{path}?basDd={targetDate:yyyyMMdd}";
var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, cfg.ApiKey, Logger, ct);
var parsed = KrxWarrantParser.ParseDaily(json, type);
Logger.LogInformation("[{Job}] {Type} basDd={TargetDate} rows={Rows}", JobName, type, targetDate, parsed.Count);
rows.AddRange(parsed);
}
if (rows.Count == 0)
{
Logger.LogInformation("[{Job}] basDd={TargetDate} 신주인수권 미반영 (0건)", JobName, targetDate);
return false;
}
var existing = await db.WarrantDailyTrade.Where(c => c.TradeDate == targetDate).ToListAsync(ct);
var existingByKey = existing.ToDictionary(c => (c.WarrantType, c.Code));
var inserted = 0;
var updated = 0;
foreach (var row in rows)
{
if (existingByKey.TryGetValue((row.WarrantType, row.Code), out var trade))
{
trade.Update(row.Name, row.Market, row.Close, row.Open, row.High, row.Low, row.ChangeAmount, row.ChangeRate, row.Volume, row.TradeValue, row.MarketCap, row.ListedShares, row.TargetStockCode, row.TargetStockName, row.TargetStockPrice, row.ExercisePrice, row.ExerciseStartDate, row.ExerciseEndDate, row.IssuePrice, row.DelistDate);
updated++;
}
else
{
var created = WarrantDailyTrade.Create(row.WarrantType, row.Code, row.Name, row.Market, row.TradeDate, row.Close, row.Open, row.High, row.Low, row.ChangeAmount, row.ChangeRate, row.Volume, row.TradeValue, row.MarketCap, row.ListedShares, row.TargetStockCode, row.TargetStockName, row.TargetStockPrice, row.ExercisePrice, row.ExerciseStartDate, row.ExerciseEndDate, row.IssuePrice, row.DelistDate);
await db.WarrantDailyTrade.AddAsync(created, ct);
existingByKey[(row.WarrantType, row.Code)] = 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;
}
}