using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Skcks.Study.AbpProject.Products;

namespace Skcks.Study.AbpProject.Web.Pages.Products;

public class CreateProductModal : AbpProjectPageModel
{
    public SelectListItem[] Categories { get; set; }

    [BindProperty]
    public CreateEditProductViewModel Product {get; set; }

    public readonly IProductAppService _productAppService;

    public CreateProductModal(IProductAppService productAppService)
    {
        _productAppService = productAppService;
    }

    public async Task OnGetAsync()
    {
        Product = new CreateEditProductViewModel
        {
            ReleaseDate = Clock.Now,
            StockState = ProductStockState.PreOrder
        };

        var categoriesAsync = await _productAppService.GetCategoriesAsync();

        Categories = categoriesAsync.Items
            .Select(x => new SelectListItem(x.Name, x.Id.ToString()))
            .ToArray();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        var productDto = ObjectMapper.Map<CreateEditProductViewModel, CreateUpdateProductDto>(Product);
        await _productAppService.CreateAsync(productDto);
        return NoContent();
    }
}