using Application.Abstractions.Crypto;
using Application.Abstractions.Messaging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Admin.Pages.Config;
public class ExternalModel(IMediator mediator, IFieldEncryptor encryptor) : PageModel
{
[BindProperty]
public InputModel Input { get; set; } = new();
public async Task OnGetAsync(CancellationToken ct)
{
var config = await mediator.Send(new GetConfig.Query(), ct);
if (config is not null)
{
Input = InputModel.From(config);
// 공개(/api/config) 응답엔 암호문(enc) 그대로 — Admin 화면에서만 복호화해 실제 키 표시
Input.DataCollection.DataGoKrServiceKey = Dec(config.DataCollection.DataGoKrServiceKey);
Input.DataCollection.KrxApiKey = Dec(config.DataCollection.KrxApiKey);
Input.DataCollection.OpenDartApiKey = Dec(config.DataCollection.OpenDartApiKey);
Input.DataCollection.KoreaEximExchangeKey = Dec(config.DataCollection.KoreaEximExchangeKey);
Input.DataCollection.KoreaEximLoanRateKey = Dec(config.DataCollection.KoreaEximLoanRateKey);
Input.DataCollection.KoreaEximIntlRateKey = Dec(config.DataCollection.KoreaEximIntlRateKey);
Input.DataCollection.SeibroApiKey = Dec(config.DataCollection.SeibroApiKey);
Input.DataCollection.KosisApiKey = Dec(config.DataCollection.KosisApiKey);
Input.External.NaverClientSecret = Dec(config.External.NaverClientSecret);
Input.External.KakaoRestApiKey = Dec(config.External.KakaoRestApiKey);
Input.External.KakaoAdminKey = Dec(config.External.KakaoAdminKey);
Input.External.NaverSearchClientSecret = Dec(config.External.NaverSearchClientSecret);
}
}
/// 암호문(enc:)이면 복호화, 아니면 그대로/빈 값 반환 — Admin 화면 표시 전용.
private string? Dec(string? enc)
{
return string.IsNullOrWhiteSpace(enc) ? null : EncryptedConfigValue.Unprotect(encryptor, enc);
}
public async Task OnPostAsync(CancellationToken ct)
{
if (!ModelState.IsValid)
{
return Page();
}
await mediator.Send(Input.ToCommand(), ct);
TempData["SuccessMessage"] = "저장되었습니다.";
return RedirectToPage();
}
public sealed class InputModel
{
public UpdateConfig.Request.ExternalApiConfigDto External { get; set; } = new();
public UpdateConfig.Request.DataCollectionConfigDto DataCollection { get; set; } = new();
public static InputModel From(GetConfig.Response config)
{
var req = UpdateConfig.Request.From(config);
return new()
{
External = req.External,
DataCollection = req.DataCollection ?? new()
};
}
public UpdateConfig.Command ToCommand()
{
return new(
External: External,
DataCollection: DataCollection
);
}
}
}