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>WorkShift master endpoints (docs/13-BACKEND-HRM-API.md §2).</summary>
[Route("api/v1/work-shifts")]
public sealed class WorkShiftsController : ApiControllerBase
{
    private readonly IWorkShiftService _shifts;

    public WorkShiftsController(IWorkShiftService shifts) => _shifts = shifts;

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

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

    [HttpPost]
    [ProducesResponseType(typeof(WorkShiftDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    public async Task<ActionResult<WorkShiftDto>> Create([FromBody] CreateWorkShiftRequest request, CancellationToken ct)
    {
        var result = await _shifts.CreateAsync(request, ct);
        SetETag(result.RowVersion);
        return Created($"/api/v1/work-shifts/{result.Value.WorkShiftId}", result.Value);
    }

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

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