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

namespace Hc900Crawler.Web.Controllers;

/// <summary>트렌드 워크스페이스 — 아날로그 포인트 · 그룹 CRUD · 실시간 tail. 이력은 기존 /api/history 재사용.</summary>
[ApiController]
[Route("api/trend")]
public class TrendController : ControllerBase
{
    private readonly ITrendService _svc;
    private readonly ILogger<TrendController> _logger;

    public TrendController(ITrendService svc, ILogger<TrendController> logger)
    {
        _svc    = svc;
        _logger = logger;
    }

    /// <summary>그룹 빌더용 아날로그 포인트 목록 (숫자 livevalue 한정)</summary>
    [HttpGet("analog-points")]
    public async Task<IActionResult> AnalogPoints([FromQuery] string? q, CancellationToken ct)
    {
        try   { return Ok(new { items = await _svc.GetAnalogPointsAsync(q ?? "", ct) }); }
        catch (Exception ex) { _logger.LogError(ex, "[Trend] analog-points 실패"); return StatusCode(500, new { error = ex.Message }); }
    }

    [HttpGet("groups")]
    public async Task<IActionResult> Groups(CancellationToken ct)
    {
        try   { return Ok(new { items = await _svc.GetGroupsAsync(ct) }); }
        catch (Exception ex) { _logger.LogError(ex, "[Trend] groups 조회 실패"); return StatusCode(500, new { error = ex.Message }); }
    }

    [HttpGet("groups/{id:int}")]
    public async Task<IActionResult> Group(int id, CancellationToken ct)
    {
        var g = await _svc.GetGroupAsync(id, ct);
        return g is null ? NotFound() : Ok(g);
    }

    [HttpPost("groups")]
    public async Task<IActionResult> Create([FromBody] TrendGroupUpsertDto dto, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(dto.Name))
            return BadRequest(new { error = "name 은 필수입니다." });
        try   { return Ok(await _svc.CreateGroupAsync(dto, ct)); }
        catch (Exception ex) { _logger.LogError(ex, "[Trend] 그룹 생성 실패"); return StatusCode(500, new { error = ex.Message }); }
    }

    [HttpPut("groups/{id:int}")]
    public async Task<IActionResult> Update(int id, [FromBody] TrendGroupUpsertDto dto, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(dto.Name))
            return BadRequest(new { error = "name 은 필수입니다." });
        var g = await _svc.UpdateGroupAsync(id, dto, ct);
        return g is null ? NotFound() : Ok(g);
    }

    [HttpDelete("groups/{id:int}")]
    public async Task<IActionResult> Delete(int id, CancellationToken ct)
        => await _svc.DeleteGroupAsync(id, ct) ? Ok(new { success = true }) : NotFound();

    /// <summary>실시간 tail — 그룹 멤버 현재값(아날로그)</summary>
    [HttpGet("live")]
    public async Task<IActionResult> Live([FromQuery] string? tags, CancellationToken ct)
    {
        var list = (tags ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        try   { return Ok(new { items = await _svc.GetLiveAsync(list, ct) }); }
        catch (Exception ex) { _logger.LogError(ex, "[Trend] live 실패"); return StatusCode(500, new { error = ex.Message }); }
    }

    /// <summary>알람 한계선 (HI/LO/SP 수평선용)</summary>
    [HttpGet("limits")]
    public async Task<IActionResult> Limits([FromQuery] string? tags, CancellationToken ct)
    {
        var list = (tags ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        try   { return Ok(new { items = await _svc.GetLimitsAsync(list, ct) }); }
        catch (Exception ex) { _logger.LogError(ex, "[Trend] limits 실패"); return StatusCode(500, new { error = ex.Message }); }
    }

    /// <summary>운전상태 밴드 (RUN/TRIP 구간)</summary>
    [HttpGet("runbands")]
    public async Task<IActionResult> RunBands([FromQuery] DateTime from, [FromQuery] DateTime to, [FromQuery] string? area, CancellationToken ct)
    {
        try   { return Ok(new { items = await _svc.GetRunBandsAsync(from, to, area, ct) }); }
        catch (Exception ex) { _logger.LogError(ex, "[Trend] runbands 실패"); return StatusCode(500, new { error = ex.Message }); }
    }
}
