using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SolutionErp.Application.Common.Models;
using SolutionErp.Application.Master.Departments;

namespace SolutionErp.Api.Controllers;

[ApiController]
[Route("api/departments")]
[Authorize]
public class DepartmentsController(IMediator mediator) : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<PagedResult<DepartmentDto>>> List(
        [FromQuery] int page = 1, [FromQuery] int pageSize = 20,
        [FromQuery] string? search = null, [FromQuery] string? sortBy = null, [FromQuery] bool sortDesc = true,
        CancellationToken ct = default)
        => Ok(await mediator.Send(new ListDepartmentsQuery { Page = page, PageSize = pageSize, Search = search, SortBy = sortBy, SortDesc = sortDesc }, ct));

    // Cây tổ chức phân cấp phòng ban (nền trang Hồ sơ Nhân sự). Authz = giống
    // [HttpGet] List ở trên (chỉ class-level [Authorize], không attribute per-action).
    [HttpGet("tree")]
    public async Task<ActionResult<List<DepartmentTreeNodeDto>>> Tree(CancellationToken ct)
        => Ok(await mediator.Send(new GetDepartmentTreeQuery(), ct));

    [HttpGet("{id:guid}")]
    public async Task<ActionResult<DepartmentDto>> Get(Guid id, CancellationToken ct)
        => Ok(await mediator.Send(new GetDepartmentQuery(id), ct));

    // [S57] Master write khóa Admin+CatalogManager (đọc mở cho mọi role; chống sửa/xóa
    // Phòng ban qua API khi mở quyền xem cho toàn bộ nhân viên).
    [Authorize(Roles = "Admin,CatalogManager")]
    [HttpPost]
    public async Task<ActionResult<Guid>> Create([FromBody] CreateDepartmentCommand cmd, CancellationToken ct)
    {
        var id = await mediator.Send(cmd, ct);
        return CreatedAtAction(nameof(Get), new { id }, new { id });
    }

    [Authorize(Roles = "Admin,CatalogManager")]
    [HttpPut("{id:guid}")]
    public async Task<IActionResult> Update(Guid id, [FromBody] UpdateDepartmentCommand cmd, CancellationToken ct)
    {
        if (id != cmd.Id) return BadRequest(new { detail = "ID không khớp" });
        await mediator.Send(cmd, ct);
        return NoContent();
    }

    [Authorize(Roles = "Admin,CatalogManager")]
    [HttpDelete("{id:guid}")]
    public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
    {
        await mediator.Send(new DeleteDepartmentCommand(id), ct);
        return NoContent();
    }
}
