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>Designation (job title) master endpoints (docs/13-BACKEND-HRM-API.md §2).</summary>
[Route("api/v1/designations")]
public sealed class DesignationsController : ApiControllerBase
{
    private readonly IDesignationService _designations;

    public DesignationsController(IDesignationService designations) => _designations = designations;

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

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

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

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

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