using ExperionCrawler.Core.Application.DTOs;
using ExperionCrawler.Core.Application.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace ExperionCrawler.Web.Controllers;

/// <summary>
/// Text-to-SQL API 컨트롤러
/// 자연어 질의를 SQL로 변환하고 시계열 데이터를 조회합니다.
/// </summary>
[ApiController]
[Route("api/text-to-sql")]
public class TextToSqlController : ControllerBase
{
    private readonly ITextToSqlService _textToSqlService;

    public TextToSqlController(ITextToSqlService textToSqlService)
    {
        _textToSqlService = textToSqlService;
    }

    /// <summary>
    /// 자연어 질의를 SQL로 변환
    /// </summary>
    [HttpPost("parse")]
    public async Task<IActionResult> Parse([FromBody] NaturalLanguageQueryDto dto)
    {
        try
        {
            var sql = await _textToSqlService.ParseNaturalLanguageAsync(dto.Query);
            return Ok(new { success = true, sql });
        }
        catch (Exception ex)
        {
            return Ok(new { success = false, error = ex.Message });
        }
    }

    /// <summary>
    /// SQL 쿼리 실행 및 결과 반환
    /// </summary>
    [HttpPost("execute")]
    public async Task<IActionResult> Execute([FromBody] SqlQueryDto dto)
    {
        var result = await _textToSqlService.ExecuteQueryAsync(dto.Sql, dto.Limit);
        return Ok(result);
    }

    /// <summary>
    /// 쿼리 제안 (자동 완성)
    /// </summary>
    [HttpGet("suggest")]
    public async Task<IActionResult> Suggest([FromQuery] string input = "")
    {
        var suggestions = await _textToSqlService.SuggestQueriesAsync(input);
        return Ok(new { success = true, suggestions });
    }

    /// <summary>
    /// 시계열 분석 (평균, 최대, 최소, 추세)
    /// </summary>
    [HttpPost("analyze")]
    public async Task<IActionResult> Analyze([FromBody] AnalyzeRequestDto dto)
    {
        var result = await _textToSqlService.AnalyzeAsync(dto);
        return Ok(result);
    }
}
