using Insight.Api;
using Insight.Domain.Models;
using Microsoft.AspNetCore.Mvc;

namespace Insight.Server.Controllers
{
    [ApiController, Route("api/update")]
    public class UpdateController : ControllerBase
    {
        private readonly ILogger<UpdateController> _logger;

        public UpdateController(ILogger<UpdateController> logger)
        {
            _logger = logger;
        }

        [HttpGet("updater/windows")]
        public IActionResult UpdaterWindows()
        {
            _logger.LogInformation("[{method}] {route} => {ep}", Request.Method, Request.HttpContext.Request.Path, Request.HttpContext.Connection.RemoteIpAddress);

            var updateDir = new DirectoryInfo($"{Locations.UpdatesPath}/updater/windows");

            if (updateDir.Exists is false)
            {
                return NotFound();
            }

            var updateLock = new FileInfo($"{updateDir.FullName}/.lock");

            if (updateLock.Exists)
            {
                return NotFound("locked");
            }

            var versions = updateDir.GetFiles("*.zip", SearchOption.TopDirectoryOnly);

            if (versions is null || versions.Any() is false) return NotFound();

            var latest = versions.OrderBy(x => x.Name).FirstOrDefault();

            if (latest is null) return NotFound();

            var relPath = $"{Path.GetRelativePath($"{Domain.Constants.Configuration.AppDirectory?.FullName}", latest.FullName)}";

            if (Version.TryParse(Path.GetFileNameWithoutExtension(latest.Name), out var fileversion) is false) return NotFound();

            return Ok(new UpdateResponse
            {
                Version = fileversion,
                Uri = new Uri($"{Request.Scheme}://{Request.Host}/api/{relPath}")
            });
        }

        [HttpGet("agent/windows")]
        public IActionResult AgentWindows()
        {
            _logger.LogInformation("[{method}] {route} => {ep}", Request.Method, Request.HttpContext.Request.Path, Request.HttpContext.Connection.RemoteIpAddress);

            var updateDir = new DirectoryInfo($"{Locations.UpdatesPath}/agent/windows");

            if (updateDir.Exists is false)
            {
                return NotFound();
            }

            var updateLock = new FileInfo($"{updateDir.FullName}/.lock");

            if (updateLock.Exists)
            {
                return NotFound("locked");
            }

            var versions = updateDir.GetFiles("*.zip", SearchOption.TopDirectoryOnly);

            if (versions is null || versions.Any() is false) return NotFound();

            var latest = versions.OrderBy(x => x.Name).FirstOrDefault();

            if (latest is null) return NotFound();

            var relPath = $"{Path.GetRelativePath($"{Domain.Constants.Configuration.AppDirectory?.FullName}", latest.FullName)}";

            if (Version.TryParse(Path.GetFileNameWithoutExtension(latest.Name), out var fileversion) is false) return NotFound();

            return Ok(new UpdateResponse
            {
                Version = fileversion,
                Uri = new Uri($"{Request.Scheme}://{Request.Host}/api/{relPath}")
            });
        }
    }
}