using System.Collections.Generic;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Application.App.Stores.Queries;
using TakeoutSaaS.Domain.Stores.Enums;
using TakeoutSaaS.Module.Authorization.Attributes;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Web.Api;

namespace TakeoutSaaS.AdminApi.Controllers;

/// <summary>
/// 门店桌码管理。
/// </summary>
[ApiVersion("1.0")]
[Authorize]
[Route("api/admin/v{version:apiVersion}/stores/{storeId:long}/tables")]
public sealed class StoreTablesController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 查询桌码列表。
    /// </summary>
    [HttpGet]
    [PermissionAuthorize("store-table:read")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<StoreTableDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<IReadOnlyList<StoreTableDto>>> List(
        long storeId,
        [FromQuery] long? areaId,
        [FromQuery] StoreTableStatus? status,
        CancellationToken cancellationToken)
    {
        var result = await mediator.Send(new ListStoreTablesQuery
        {
            StoreId = storeId,
            AreaId = areaId,
            Status = status
        }, cancellationToken);

        return ApiResponse<IReadOnlyList<StoreTableDto>>.Ok(result);
    }

    /// <summary>
    /// 批量生成桌码。
    /// </summary>
    [HttpPost]
    [PermissionAuthorize("store-table:create")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<StoreTableDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<IReadOnlyList<StoreTableDto>>> Generate(long storeId, [FromBody] GenerateStoreTablesCommand command, CancellationToken cancellationToken)
    {
        if (command.StoreId == 0)
        {
            command = command with { StoreId = storeId };
        }

        var result = await mediator.Send(command, cancellationToken);
        return ApiResponse<IReadOnlyList<StoreTableDto>>.Ok(result);
    }

    /// <summary>
    /// 更新桌码。
    /// </summary>
    [HttpPut("{tableId:long}")]
    [PermissionAuthorize("store-table:update")]
    [ProducesResponseType(typeof(ApiResponse<StoreTableDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<StoreTableDto>> Update(long storeId, long tableId, [FromBody] UpdateStoreTableCommand command, CancellationToken cancellationToken)
    {
        if (command.StoreId == 0 || command.TableId == 0)
        {
            command = command with { StoreId = storeId, TableId = tableId };
        }

        var result = await mediator.Send(command, cancellationToken);
        return result == null
            ? ApiResponse<StoreTableDto>.Error(ErrorCodes.NotFound, "桌码不存在")
            : ApiResponse<StoreTableDto>.Ok(result);
    }

    /// <summary>
    /// 删除桌码。
    /// </summary>
    [HttpDelete("{tableId:long}")]
    [PermissionAuthorize("store-table:delete")]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<object>> Delete(long storeId, long tableId, CancellationToken cancellationToken)
    {
        var success = await mediator.Send(new DeleteStoreTableCommand { StoreId = storeId, TableId = tableId }, cancellationToken);
        return success
            ? ApiResponse<object>.Ok(null)
            : ApiResponse<object>.Error(ErrorCodes.NotFound, "桌码不存在");
    }

    /// <summary>
    /// 导出桌码二维码 ZIP。
    /// </summary>
    [HttpPost("export")]
    [PermissionAuthorize("store-table:export")]
    [ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Export(long storeId, [FromBody] ExportStoreTableQRCodesQuery query, CancellationToken cancellationToken)
    {
        if (query.StoreId == 0)
        {
            query = query with { StoreId = storeId };
        }

        var result = await mediator.Send(query, cancellationToken);
        if (result is null)
        {
            return Ok(ApiResponse<object>.Error(ErrorCodes.NotFound, "未找到可导出的桌码"));
        }

        return File(result.Content, result.ContentType, result.FileName);
    }
}
