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

namespace Meezi.API.Controllers;

[Route("api/cafes/{cafeId}/taxes")]
public class TaxesController : CafeApiControllerBase
{
    private readonly ITaxService _taxService;

    public TaxesController(ITaxService taxService) => _taxService = taxService;

    [HttpGet]
    public async Task<IActionResult> GetAll(string cafeId, ITenantContext tenant, CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _taxService.GetAllAsync(cafeId, cancellationToken);
        return Ok(new ApiResponse<IReadOnlyList<TaxDto>>(true, data));
    }

    [HttpPost]
    public async Task<IActionResult> Create(
        string cafeId,
        [FromBody] CreateTaxRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureOwner(tenant) is { } ownerDenied) return ownerDenied;
        var data = await _taxService.CreateAsync(cafeId, request, cancellationToken);
        return Ok(new ApiResponse<TaxDto>(true, data));
    }

    [HttpPatch("{id}")]
    public async Task<IActionResult> Update(
        string cafeId,
        string id,
        [FromBody] UpdateTaxRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureOwner(tenant) is { } ownerDenied) return ownerDenied;
        var data = await _taxService.UpdateAsync(cafeId, id, request, cancellationToken);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<TaxDto>(true, data));
    }

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