using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using LittleShop.DTOs;
using LittleShop.Services;

namespace LittleShop.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = "Bearer")]
public class ProductVariationsController : ControllerBase
{
    private readonly IProductService _productService;

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

    [HttpGet("product/{productId}")]
    public async Task<ActionResult<IEnumerable<ProductVariationDto>>> GetProductVariations(Guid productId)
    {
        var variations = await _productService.GetProductVariationsAsync(productId);
        return Ok(variations);
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<ProductVariationDto>> GetProductVariation(Guid id)
    {
        var variation = await _productService.GetProductVariationByIdAsync(id);
        if (variation == null)
            return NotFound();

        return Ok(variation);
    }

    [HttpPost]
    [Authorize(Roles = "Admin")]
    public async Task<ActionResult<ProductVariationDto>> CreateProductVariation(CreateProductVariationDto createVariationDto)
    {
        try
        {
            var variation = await _productService.CreateProductVariationAsync(createVariationDto);
            return CreatedAtAction(nameof(GetProductVariation), new { id = variation.Id }, variation);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    [HttpPut("{id}")]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> UpdateProductVariation(Guid id, UpdateProductVariationDto updateVariationDto)
    {
        var success = await _productService.UpdateProductVariationAsync(id, updateVariationDto);
        if (!success)
            return NotFound();

        return NoContent();
    }

    [HttpDelete("{id}")]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> DeleteProductVariation(Guid id)
    {
        var success = await _productService.DeleteProductVariationAsync(id);
        if (!success)
            return NotFound();

        return NoContent();
    }
}