using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using Meezi.API.Models.Kitchen;
using Meezi.API.Services;
using Meezi.Core.Interfaces;
using Meezi.Shared;

namespace Meezi.API.Controllers;

[Route("api/cafes/{cafeId}/kitchen-stations")]
public class KitchenStationsController : CafeApiControllerBase
{
    private readonly IKitchenStationService _stations;
    private readonly IValidator<CreateKitchenStationRequest> _createValidator;
    private readonly IValidator<UpdateKitchenStationRequest> _updateValidator;

    public KitchenStationsController(
        IKitchenStationService stations,
        IValidator<CreateKitchenStationRequest> createValidator,
        IValidator<UpdateKitchenStationRequest> updateValidator)
    {
        _stations = stations;
        _createValidator = createValidator;
        _updateValidator = updateValidator;
    }

    [HttpGet]
    public async Task<IActionResult> List(string cafeId, ITenantContext tenant, CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _stations.ListAsync(cafeId, ct);
        return Ok(new ApiResponse<IReadOnlyList<KitchenStationDto>>(true, data));
    }

    [HttpPost]
    public async Task<IActionResult> Create(
        string cafeId,
        [FromBody] CreateKitchenStationRequest request,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var validation = await _createValidator.ValidateAsync(request, ct);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var data = await _stations.CreateAsync(cafeId, request, ct);
        if (data is null)
            return BadRequest(new ApiResponse<object>(false, null, new ApiError("INVALID_BRANCH", "Branch not found.")));

        return Ok(new ApiResponse<KitchenStationDto>(true, data));
    }

    [HttpPatch("{id}")]
    public async Task<IActionResult> Update(
        string cafeId,
        string id,
        [FromBody] UpdateKitchenStationRequest request,
        ITenantContext tenant,
        CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var validation = await _updateValidator.ValidateAsync(request, ct);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var data = await _stations.UpdateAsync(cafeId, id, request, ct);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<KitchenStationDto>(true, data));
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(string cafeId, string id, ITenantContext tenant, CancellationToken ct)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var ok = await _stations.DeleteAsync(cafeId, id, ct);
        if (!ok) return NotFoundError();
        return Ok(new ApiResponse<object>(true, new { id }));
    }
}
