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>SalaryComponent master endpoints (docs/13-BACKEND-HRM-API.md §6).</summary>
[Route("api/v1/salary-components")]
public sealed class SalaryComponentsController : ApiControllerBase
{
    private readonly ISalaryComponentService _components;

    public SalaryComponentsController(ISalaryComponentService components) => _components = components;

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

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

    [HttpPost]
    [ProducesResponseType(typeof(SalaryComponentDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    public async Task<ActionResult<SalaryComponentDto>> Create([FromBody] CreateSalaryComponentRequest request, CancellationToken ct)
    {
        var result = await _components.CreateAsync(request, ct);
        SetETag(result.RowVersion);
        return Created($"/api/v1/salary-components/{result.Value.SalaryComponentId}", result.Value);
    }

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

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