using Microsoft.AspNetCore.Mvc;
using LogCentral.Server.Services;
using LogCentral.Server.Models;

namespace LogCentral.Server.Controllers;

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

    public LogsController(ILogService logService)
    {
        _logService = logService;
    }

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

        // Map DTO -> EF entity
        var logEntities = entries.Select(dto => new LogEntry
        {
            Id = dto.Id,
            Timestamp = dto.Timestamp,
            ApplicationName = dto.ApplicationName,
            ApplicationVersion = dto.ApplicationVersion,
            Environment = dto.Environment,
            MachineName = dto.MachineName,
            Level = dto.Level,
            Category = dto.Category,
            Message = dto.Message,
            Exception = dto.Exception,
            StackTrace = dto.StackTrace,
            Properties = dto.Properties,
            UserId = dto.UserId,
            SessionId = dto.SessionId,
            RequestId = dto.RequestId,
            CorrelationId = dto.CorrelationId
        }).ToList();

        await _logService.AddLogsAsync(logEntities);

        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)
    {
        var stats = await _logService.GetStatsAsync(app, env);
        return Ok(stats);
    }
}