using Microsoft.AspNetCore.Mvc;
using Meezi.Admin.API.Models;
using Meezi.Admin.API.Services;
using Meezi.Shared;

namespace Meezi.Admin.API.Controllers;

[Route("api/admin/cafes")]
public class AdminCafesController : AdminApiControllerBase
{
    private readonly IAdminPlatformService _platform;

    public AdminCafesController(IAdminPlatformService platform)
    {
        _platform = platform;
    }

    [HttpGet]
    public async Task<IActionResult> List(CancellationToken cancellationToken)
    {
        var cafes = await _platform.ListCafesAsync(cancellationToken);
        return Ok(new ApiResponse<object>(true, cafes));
    }

    [HttpPatch("{cafeId}")]
    public async Task<IActionResult> Patch(string cafeId, [FromBody] AdminCafePatchRequest request, CancellationToken cancellationToken)
    {
        var ok = await _platform.PatchCafeAsync(cafeId, request, cancellationToken);
        if (!ok)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Cafe not found.")));

        return Ok(new ApiResponse<object>(true, new { cafeId }));
    }

    [HttpPut("{cafeId}/features")]
    public async Task<IActionResult> SetFeature(
        string cafeId,
        [FromBody] CafeFeatureOverrideRequest request,
        CancellationToken cancellationToken)
    {
        var ok = await _platform.SetCafeFeatureOverrideAsync(cafeId, request, cancellationToken);
        if (!ok)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Cafe not found.")));

        return Ok(new ApiResponse<object>(true, new { cafeId, request.FeatureKey, request.IsEnabled }));
    }

    [HttpGet("{cafeId}/discover-profile")]
    public async Task<IActionResult> GetDiscoverProfile(string cafeId, CancellationToken cancellationToken)
    {
        var data = await _platform.GetCafeDiscoverProfileAsync(cafeId, cancellationToken);
        if (data is null)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Cafe not found.")));

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

    [HttpPut("{cafeId}/discover-profile")]
    public async Task<IActionResult> PutDiscoverProfile(
        string cafeId,
        [FromBody] AdminUpsertCafeDiscoverProfileRequest request,
        CancellationToken cancellationToken)
    {
        var data = await _platform.UpsertCafeDiscoverProfileAsync(cafeId, request, cancellationToken);
        if (data is null)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Cafe not found.")));

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