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;
///
/// T+1 일별 시세 수집 — 금융위 주식시세정보 API (영업일+1 13시 이후 반영).
/// 기본 13:10 KST 실행, basDt=직전 영업일 전량 수집 → StockDailyPrice upsert + Stock denorm(최근 종가/등락률/시총) 갱신.
/// 미반영(0건)이면 2시간 간격 2회 재시도 (≈15시/17시). ServiceKey 미설정 시 로그만 남기고 skip.
///
internal sealed class DailyPriceSyncService(
IServiceScopeFactory scopeFactory,
IHttpClientFactory httpClientFactory,
IOptions settings,
ILogger logger
) : DailyScheduledService(logger)
{
private const string ServicePath = "/1160100/service/GetStockSecuritiesInfoService/getStockPriceInfo";
private const int MaxPages = 50;
protected override string JobName => "DailyPriceSync";
protected override TimeOnly TargetTime => ParseTime(settings.Value.StockData.DailyPriceSyncTime, new TimeOnly(13, 10));
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.StockData.DataGoKr;
if (string.IsNullOrWhiteSpace(cfg.ServiceKey))
{
Logger.LogWarning("[{Job}] StockData:DataGoKr:ServiceKey 미설정 — 수집 skip", JobName);
return true;
}
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
var client = httpClientFactory.CreateClient(DataGoKrHttp.ClientName);
var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst, ct);
var rows = new List();
var totalCount = int.MaxValue;
for (var pageNo = 1; pageNo <= MaxPages && rows.Count < totalCount; pageNo++)
{
var url = $"{cfg.BaseUrl.TrimEnd('/')}{ServicePath}?serviceKey={Uri.EscapeDataString(cfg.ServiceKey)}&resultType=json&numOfRows={cfg.PageSize}&pageNo={pageNo}&basDt={targetDate:yyyyMMdd}";
var json = await DataGoKrHttp.GetStringWithRetryAsync(client, url, Logger, ct);
var (items, total) = DataGoKrStockParser.ParseDailyPrices(json);
totalCount = total;
if (items.Count == 0)
{
break;
}
rows.AddRange(items);
}
if (rows.Count == 0)
{
Logger.LogInformation("[{Job}] basDt={TargetDate} 시세 미반영 (0건)", JobName, targetDate);
return false;
}
var stockByCode = await db.Stock.ToDictionaryAsync(c => c.Code, ct);
var existingByStockID = await db.StockDailyPrice.Where(c => c.TradingDate == targetDate).ToDictionaryAsync(c => c.StockID, ct);
var inserted = 0;
var updated = 0;
var unknown = 0;
foreach (var row in rows)
{
if (!stockByCode.TryGetValue(row.Code, out var stock))
{
// 마스터 미동기화 종목 — 다음 마스터 동기화 후 자연 반영
unknown++;
continue;
}
if (existingByStockID.TryGetValue(stock.ID, out var price))
{
price.Update(row.Open, row.High, row.Low, row.Close, row.Volume, row.TradingValue, row.ChangeAmount, row.ChangeRate, row.MarketCap, row.ListedShares);
updated++;
}
else
{
await db.StockDailyPrice.AddAsync(StockDailyPrice.Create(stock.ID, row.TradingDate, row.Open, row.High, row.Low, row.Close, row.Volume, row.TradingValue, row.ChangeAmount, row.ChangeRate, row.MarketCap, row.ListedShares), ct);
inserted++;
}
stock.UpdateLastPrice(row.TradingDate, row.Close, row.ChangeRate, row.MarketCap);
}
await db.SaveChangesAsync(ct);
Logger.LogInformation("[{Job}] 완료 — basDt={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}, unknownCode={Unknown}",
JobName, targetDate, rows.Count, inserted, updated, unknown);
return true;
}
}