using Microsoft.AspNetCore.Mvc;
using TF6760ApiTest.Services;
using TF6760ApiTest.Models;

namespace TF6760ApiTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProductController : ControllerBase
    {
        private readonly IProductService productService;
        private readonly ILogger<ProductController> logger;

        public ProductController(IProductService productService, ILogger<ProductController> logger)
        {
            this.productService = productService;
            this.logger = logger;
        }

        // 根据ID获取产品
        [HttpGet("{id}")]
        public async Task<ActionResult<Product>> GetById(int id)
        {
            var product = await productService.GetProductByIdAsync(id);
            if (product == null)
                return NotFound();
            return Ok(product);
        }

        // 根据 BarCode 获取产品
        [HttpGet("barcode/{barCode}")]
        public async Task<ActionResult<Product>> GetByBarCode(string barCode)
        {
            logger.LogInformation("查询 BarCode: {BarCode}", barCode);
            var product = await productService.GetProductByBarCodeAsync(barCode);
            if (product == null)
            {
                logger.LogWarning("未找到 BarCode: {BarCode}", barCode);
                return NotFound();
            }
            logger.LogInformation("找到 BarCode: {BarCode}", barCode);
            return Ok(product);
        }

        // 新增产品
        [HttpPost]
        public async Task<ActionResult<Product>> Add([FromBody] Product product)
        {
            try
            {
                var created = await productService.AddProductAsync(product);
                return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
            }
            catch (InvalidOperationException ex)
            {
                // 条码重复，返回 409 Conflict
                return Conflict(ex.Message);
            }
        }

        // 更新产品（根据 BarCode）
        [HttpPut]
        public async Task<ActionResult<Product>> Update(Product product)
        {
            var updated = await productService.UpdateProductAsync(product);
            if (updated == null)
                return NotFound();
            return Ok(updated);
        }

        // 删除产品
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            var existing = await productService.GetProductByIdAsync(id);
            if (existing == null)
                return NotFound();

            await productService.DeleteProductAsync(id);
            return NoContent();
        }

        // 根据 BarCode 删除产品
        [HttpDelete("barcode/{barCode}")]
        public async Task<IActionResult> DeleteByBarCode(string barCode)
        {
            logger.LogInformation("尝试删除 BarCode: {BarCode}", barCode);
            var existing = await productService.GetProductByBarCodeAsync(barCode);
            if (existing == null)
            {
                logger.LogWarning("未找到 BarCode: {BarCode}", barCode);
                return NotFound();
            }

            await productService.DeleteProductByBarCodeAsync(barCode);
            logger.LogInformation("已删除 BarCode: {BarCode}", barCode);
            return NoContent();
        }

        // 分页获取产品
        [HttpGet("paged")]
        public async Task<ActionResult<PagedResult<Product>>> GetPaged([FromQuery] int pageNumber = 1, [FromQuery] int pageSize = 10)
        {
            logger.LogInformation("分页查询: 页码={PageNumber}, 每页数量={PageSize}", pageNumber, pageSize);
            if (pageNumber <= 0 || pageSize <= 0)
                return BadRequest("页码和每页数量必须大于0");

            var pagedResult = await productService.GetProductsPagedAsync(pageNumber, pageSize);
            return Ok(pagedResult);
        }
    }
}
