using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
using isnd.Services;
using isnd.Entities;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using NuGet.Versioning;
using isnd.Data.Packages.Catalog;
using isnd.Data.Catalog;
using isn.abst;

namespace isnd.Controllers
{
    public partial class PackagesController
    {

        // https://docs.microsoft.com/en-us/nuget/api/catalog-resource#versioning
        [HttpGet("~" + Constants.ApiVersion + ApiConfig.Catalog)]
        public async Task<IActionResult> CatalogIndex()
        {
            return Ok(await packageManager.GetCatalogIndexAsync());
        }


        [HttpGet("~" + Constants.ApiVersion + ApiConfig.Registration + "/{id}/{version?}")]
        public async Task<IActionResult> CatalogRegistration(string id, string version)
        {
            if (string.IsNullOrWhiteSpace(version))
            {
                var query = new Data.Catalog.RegistrationPageIndexQuery
                {
                    Query = id,
                    Prerelease = true
                };
                var index = await packageManager.GetPackageRegistrationIndexAsync(query);
                if (index == null) return NotFound();
                // query.TotalHits = result.Items.Select(i=>i.Items.Length).Aggregate((a,b)=>a+b);
                return Ok(index);
            }
            // return a Package
            var leaf = await packageManager.GetCatalogEntryAsync(id, version, null);
         
            if (null == leaf) return NotFound(new { id, version });
            return Ok(leaf);
        }



    }
}