using CartWise.Application.Interfaces;
using CartWise.Web.ViewModels.Product;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace CartWise.Web.Controllers;

[Authorize]
public class ProductController : Controller
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet("products/search")]
    public async Task<IActionResult> Search(string? q)
    {
        var results = string.IsNullOrWhiteSpace(q)
            ? []
            : await _productService.SearchAsync(q);

        var viewModel = new ProductSearchViewModel
        {
            Query = q,
            Results = results.Select(r => new ProductSearchResultViewModel
            {
                ProductId = r.ProductId,
                Name = r.Name,
                BrandName = r.BrandName,
                PackageDisplay = r.PackageDisplay,
                ImageUrl = r.ImageUrl
            }).ToList()
        };

        return View(viewModel);
    }

    [HttpGet("products/{id:guid}")]
    public async Task<IActionResult> Details(Guid id)
    {
        var details = await _productService.GetDetailsAsync(id);
        if (details is null)
        {
            return NotFound();
        }

        var viewModel = new ProductDetailsViewModel
        {
            ProductId = details.ProductId,
            Name = details.Name,
            BrandName = details.BrandName,
            ConceptName = details.ConceptName,
            PackageDisplay = details.PackageDisplay,
            ImageUrl = details.ImageUrl,
            BarcodeIdentifiers = details.BarcodeIdentifiers.ToList()
        };

        return View(viewModel);
    }

    [HttpGet("products/barcode/{barcode}")]
    public async Task<IActionResult> Barcode(string barcode)
    {
        var result = await _productService.ResolveBarcodeAsync(barcode);
        if (!result.IsSuccess)
        {
            return NotFound(result.Error);
        }

        return RedirectToAction(nameof(Details), new { id = result.Value!.ProductId });
    }

    [HttpGet("api/products/barcode/{barcode}")]
    public async Task<IActionResult> BarcodeJson(string barcode)
    {
        var result = await _productService.ResolveBarcodeAsync(barcode);
        if (!result.IsSuccess)
        {
            return Ok(new { found = false, error = result.Error });
        }

        return Ok(new
        {
            found = true,
            productId = result.Value!.ProductId,
            redirectUrl = Url.Action(nameof(Details), new { id = result.Value.ProductId })
        });
    }
}
