using ERPCore.Domain.Enums;
using ERPCore.Dtos.Brands;
using ERPCore.Dtos.Common;
using ERPCore.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace ERPCore.Controllers;

/// <summary>Brand master endpoints (docs/11-BACKEND-PHASE1.md §2.6).</summary>
[Route("api/v1/brands")]
public sealed class BrandsController : ApiControllerBase
{
    private readonly IBrandService _brands;

    public BrandsController(IBrandService brands) => _brands = brands;

    [HttpGet]
    [ProducesResponseType(typeof(PagedResponse<BrandDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<PagedResponse<BrandDto>>> List(
        [FromQuery] PageQuery query, [FromQuery] EntityStatus? status, CancellationToken ct)
        => Ok(await _brands.ListAsync(query, status, ct));

    [HttpGet("{brandId:int}")]
    [ProducesResponseType(typeof(BrandDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<BrandDto>> GetById(int brandId, CancellationToken ct)
    {
        var result = await _brands.GetAsync(brandId, ct);
        if (result is null) return NotFound();

        SetETag(result.RowVersion);
        return Ok(result.Value);
    }

    [HttpPost]
    [ProducesResponseType(typeof(BrandDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    public async Task<ActionResult<BrandDto>> Create([FromBody] CreateBrandRequest request, CancellationToken ct)
    {
        var result = await _brands.CreateAsync(request, ct);
        SetETag(result.RowVersion);
        return Created($"/api/v1/brands/{result.Value.BrandId}", result.Value);
    }

    [HttpPut("{brandId:int}")]
    [ProducesResponseType(typeof(BrandDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    [ProducesResponseType(StatusCodes.Status412PreconditionFailed)]
    public async Task<ActionResult<BrandDto>> Update(int brandId, [FromBody] UpdateBrandRequest request, CancellationToken ct)
    {
        var expected = RequireIfMatch();
        var result = await _brands.UpdateAsync(brandId, request, expected, ct);
        SetETag(result.RowVersion);
        return Ok(result.Value);
    }

    /// <summary>Deactivate/reactivate. Masters are never hard-deleted (FR-MD-08).</summary>
    [HttpPatch("{brandId:int}/status")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> SetStatus(int brandId, [FromBody] UpdateBrandStatusRequest request, CancellationToken ct)
    {
        await _brands.SetStatusAsync(brandId, request.Status, ct);
        return NoContent();
    }
}
