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>EmploymentType master endpoints (docs/13-BACKEND-HRM-API.md §2).</summary>
[Route("api/v1/employment-types")]
public sealed class EmploymentTypesController : ApiControllerBase
{
    private readonly IEmploymentTypeService _employmentTypes;

    public EmploymentTypesController(IEmploymentTypeService employmentTypes) => _employmentTypes = employmentTypes;

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

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

    [HttpPost]
    [ProducesResponseType(typeof(EmploymentTypeDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    public async Task<ActionResult<EmploymentTypeDto>> Create([FromBody] CreateEmploymentTypeRequest request, CancellationToken ct)
    {
        var result = await _employmentTypes.CreateAsync(request, ct);
        SetETag(result.RowVersion);
        return Created($"/api/v1/employment-types/{result.Value.EmploymentTypeId}", result.Value);
    }

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

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