using Microsoft.AspNetCore.Mvc;
using EonaCat.Logger.Server.Services;
using EonaCat.Logger.Server.Models;

namespace EonaCat.Logger.Server.Controllers;

[ApiController]
[Route("api/[controller]")]
public class LogsController : ControllerBase
{
    private readonly ILogService _logService;
    private readonly ISearchService _searchService;
    private readonly IAnalyticsService _analyticsService;

    public LogsController(ILogService logService, ISearchService searchService, IAnalyticsService analyticsService)
    {
        _logService = logService;
        _searchService = searchService;
        _analyticsService = analyticsService;
    }

    [HttpPost("batch")]
    public async Task<IActionResult> PostBatch([FromBody] List<LogEntry> entries)
    {
        var apiKey = Request.Headers["X-API-Key"].FirstOrDefault();
        if (string.IsNullOrEmpty(apiKey) || !await _logService.ValidateApiKeyAsync(apiKey))
        {
            return Unauthorized(new { error = "Invalid API key" });
        }


        await _logService.AddLogsAsync(entries);
        return Ok(new { success = true, count = entries.Count });
    }

    [HttpGet]
    public async Task<IActionResult> GetLogs([FromQuery] LogQueryParams queryParams)
    {
        var result = await _logService.GetLogsAsync(queryParams);
        return Ok(result);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetLog(string id)
    {
        var log = await _logService.GetLogByIdAsync(id);
        if (log == null) return NotFound();
        return Ok(log);
    }

    [HttpGet("stats")]
    public async Task<IActionResult> GetStats([FromQuery] string? app, [FromQuery] string? env, [FromQuery] bool skipCache = false)
    {
        var stats = await _logService.GetStatsAsync(app, env, skipCache);
        return Ok(stats);
    }

    [HttpGet("applications")]
    public async Task<IActionResult> GetApplications()
    {
        var apps = await _logService.GetApplicationsAsync();
        return Ok(apps);
    }

    [HttpGet("environments")]
    public async Task<IActionResult> GetEnvironments()
    {
        var envs = await _logService.GetEnvironmentsAsync();
        return Ok(envs);
    }

    [HttpGet("trend")]
    public async Task<IActionResult> GetTrend([FromQuery] int hours = 24)
    {
        var trend = await _logService.GetLogTrendAsync(hours);
        return Ok(trend);
    }

    [HttpPost("search")]
    public async Task<IActionResult> Search([FromBody] SearchRequest request)
    {
        var results = await _searchService.SearchAsync(request);
        return Ok(results);
    }

    [HttpGet("analytics")]
    public async Task<IActionResult> GetAnalytics([FromQuery] DateTime? start, [FromQuery] DateTime? end)
    {
        var startDate = start ?? DateTime.UtcNow.AddDays(-7);
        var endDate = end ?? DateTime.UtcNow;
        var analytics = await _analyticsService.GetAnalyticsAsync(startDate, endDate);
        return Ok(analytics);
    }
}