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

namespace ERPCore.Controllers.Hrm;

/// <summary>Branch master endpoints (docs/13-BACKEND-HRM-API.md §2).</summary>
[Route("api/v1/branches")]
public sealed class BranchesController : ApiControllerBase
{
    private readonly IBranchService _branches;

    public BranchesController(IBranchService branches) => _branches = branches;

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

    [HttpGet("{branchId:int}")]
    [ProducesResponseType(typeof(BranchDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<BranchDto>> GetById(int branchId, CancellationToken ct)
    {
        var result = await _branches.GetAsync(branchId, ct);
        if (result is null) return NotFound();
        SetETag(result.RowVersion);
        return Ok(result.Value);
    }

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

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

    [HttpPatch("{branchId:int}/status")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> SetStatus(int branchId, [FromBody] UpdateHrMasterStatusRequest request, CancellationToken ct)
    {
        await _branches.SetStatusAsync(branchId, request.Status, ct);
        return NoContent();
    }
}
