using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.Merchants.Commands;
using TakeoutSaaS.Application.App.Merchants.Dto;
using TakeoutSaaS.Application.App.Merchants.Queries;
using TakeoutSaaS.Domain.Merchants.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}/merchants")]
public sealed class MerchantsController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 创建商户。
    /// </summary>
    /// <param name="command">创建命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>创建后的商户。</returns>
    [HttpPost]
    [PermissionAuthorize("merchant:create")]
    [ProducesResponseType(typeof(ApiResponse<MerchantDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<MerchantDto>> Create([FromBody] CreateMerchantCommand command, CancellationToken cancellationToken)
    {
        // 1. 创建商户
        var result = await mediator.Send(command, cancellationToken);

        // 2. 返回创建结果
        return ApiResponse<MerchantDto>.Ok(result);
    }

    /// <summary>
    /// 查询商户列表。
    /// </summary>
    /// <param name="status">状态筛选。</param>
    /// <param name="page">页码。</param>
    /// <param name="pageSize">每页大小。</param>
    /// <param name="sortBy">排序字段。</param>
    /// <param name="sortDesc">是否倒序。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>商户分页结果。</returns>
    [HttpGet]
    [PermissionAuthorize("merchant:read")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<MerchantDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<MerchantDto>>> List(
        [FromQuery] MerchantStatus? status,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        [FromQuery] string? sortBy = null,
        [FromQuery] bool sortDesc = true,
        CancellationToken cancellationToken = default)
    {
        // 1. 组装查询参数并执行查询
        var result = await mediator.Send(new SearchMerchantsQuery
        {
            Status = status,
            Page = page,
            PageSize = pageSize,
            SortBy = sortBy,
            SortDescending = sortDesc
        }, cancellationToken);

        // 2. 返回分页结果
        return ApiResponse<PagedResult<MerchantDto>>.Ok(result);
    }

    /// <summary>
    /// 更新商户。
    /// </summary>
    /// <param name="merchantId">商户 ID。</param>
    /// <param name="command">更新命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>更新后的商户或未找到。</returns>
    [HttpPut("{merchantId:long}")]
    [PermissionAuthorize("merchant:update")]
    [ProducesResponseType(typeof(ApiResponse<MerchantDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<MerchantDto>> Update(long merchantId, [FromBody] UpdateMerchantCommand command, CancellationToken cancellationToken)
    {
        // 1. 绑定商户标识
        if (command.MerchantId == 0)
        {
            command = command with { MerchantId = merchantId };
        }

        // 2. 执行更新
        var result = await mediator.Send(command, cancellationToken);

        // 3. 返回更新结果或 404
        return result == null
            ? ApiResponse<MerchantDto>.Error(ErrorCodes.NotFound, "商户不存在")
            : ApiResponse<MerchantDto>.Ok(result);
    }

    /// <summary>
    /// 删除商户。
    /// </summary>
    /// <param name="merchantId">商户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>删除结果。</returns>
    [HttpDelete("{merchantId:long}")]
    [PermissionAuthorize("merchant:delete")]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<object>> Delete(long merchantId, CancellationToken cancellationToken)
    {
        // 1. 执行删除
        var success = await mediator.Send(new DeleteMerchantCommand { MerchantId = merchantId }, cancellationToken);

        // 2. 返回删除结果或 404
        return success
            ? ApiResponse<object>.Ok(null)
            : ApiResponse<object>.Error(ErrorCodes.NotFound, "商户不存在");
    }

    /// <summary>
    /// 获取商户概览。
    /// </summary>
    /// <param name="merchantId">商户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>商户概览或未找到。</returns>
    [HttpGet("{merchantId:long}")]
    [PermissionAuthorize("merchant:read")]
    [ProducesResponseType(typeof(ApiResponse<MerchantDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<MerchantDto>> Detail(long merchantId, CancellationToken cancellationToken)
    {
        // 1. 查询商户概览
        var result = await mediator.Send(new GetMerchantByIdQuery { MerchantId = merchantId }, cancellationToken);

        // 2. 返回结果或 404
        return result == null
            ? ApiResponse<MerchantDto>.Error(ErrorCodes.NotFound, "商户不存在")
            : ApiResponse<MerchantDto>.Ok(result);
    }

    /// <summary>
    /// 获取商户详细资料（含证照、合同）。
    /// </summary>
    /// <returns>创建的证照信息。</returns>
    [HttpGet("{merchantId:long}/detail")]
    [PermissionAuthorize("merchant:read")]
    [ProducesResponseType(typeof(ApiResponse<MerchantDetailDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<MerchantDetailDto>> FullDetail(long merchantId, CancellationToken cancellationToken)
    {
        // 1. 查询商户详细资料
        var result = await mediator.Send(new GetMerchantDetailQuery(merchantId), cancellationToken);

        // 2. 返回详情
        return ApiResponse<MerchantDetailDto>.Ok(result);
    }

    /// <summary>
    /// 上传商户证照信息（先通过文件上传接口获取 COS 地址）。
    /// </summary>
    /// <returns>创建的证照信息。</returns>
    [HttpPost("{merchantId:long}/documents")]
    [PermissionAuthorize("merchant:update")]
    [ProducesResponseType(typeof(ApiResponse<MerchantDocumentDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<MerchantDocumentDto>> CreateDocument(
        long merchantId,
        [FromBody] AddMerchantDocumentCommand body,
        CancellationToken cancellationToken)
    {
        // 1. 绑定商户标识
        var command = body with { MerchantId = merchantId };

        // 2. 创建证照记录
        var result = await mediator.Send(command, cancellationToken);
        return ApiResponse<MerchantDocumentDto>.Ok(result);
    }

    /// <summary>
    /// 商户证照列表。
    /// </summary>
    /// <returns>商户证照列表。</returns>
    [HttpGet("{merchantId:long}/documents")]
    [PermissionAuthorize("merchant:read")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<MerchantDocumentDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<IReadOnlyList<MerchantDocumentDto>>> Documents(long merchantId, CancellationToken cancellationToken)
    {
        // 1. 查询证照列表
        var result = await mediator.Send(new GetMerchantDocumentsQuery(merchantId), cancellationToken);

        // 2. 返回证照集合
        return ApiResponse<IReadOnlyList<MerchantDocumentDto>>.Ok(result);
    }

    /// <summary>
    /// 审核指定证照。
    /// </summary>
    /// <returns>审核后的证照信息。</returns>
    [HttpPost("{merchantId:long}/documents/{documentId:long}/review")]
    [PermissionAuthorize("merchant:review")]
    [ProducesResponseType(typeof(ApiResponse<MerchantDocumentDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<MerchantDocumentDto>> ReviewDocument(
        long merchantId,
        long documentId,
        [FromBody] ReviewMerchantDocumentCommand body,
        CancellationToken cancellationToken)
    {
        // 1. 绑定商户与证照标识
        var command = body with { MerchantId = merchantId, DocumentId = documentId };

        // 2. 执行审核
        var result = await mediator.Send(command, cancellationToken);
        return ApiResponse<MerchantDocumentDto>.Ok(result);
    }

    /// <summary>
    /// 新增商户合同。
    /// </summary>
    /// <returns>创建的合同信息。</returns>
    [HttpPost("{merchantId:long}/contracts")]
    [PermissionAuthorize("merchant:update")]
    [ProducesResponseType(typeof(ApiResponse<MerchantContractDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<MerchantContractDto>> CreateContract(
        long merchantId,
        [FromBody] CreateMerchantContractCommand body,
        CancellationToken cancellationToken)
    {
        // 1. 绑定商户标识
        var command = body with { MerchantId = merchantId };

        // 2. 创建合同
        var result = await mediator.Send(command, cancellationToken);
        return ApiResponse<MerchantContractDto>.Ok(result);
    }

    /// <summary>
    /// 合同列表。
    /// </summary>
    /// <returns>商户合同列表。</returns>
    [HttpGet("{merchantId:long}/contracts")]
    [PermissionAuthorize("merchant:read")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<MerchantContractDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<IReadOnlyList<MerchantContractDto>>> Contracts(long merchantId, CancellationToken cancellationToken)
    {
        // 1. 查询合同列表
        var result = await mediator.Send(new GetMerchantContractsQuery(merchantId), cancellationToken);

        // 2. 返回合同集合
        return ApiResponse<IReadOnlyList<MerchantContractDto>>.Ok(result);
    }

    /// <summary>
    /// 更新合同状态（生效/终止等）。
    /// </summary>
    /// <returns>更新后的合同信息。</returns>
    [HttpPut("{merchantId:long}/contracts/{contractId:long}/status")]
    [PermissionAuthorize("merchant:update")]
    [ProducesResponseType(typeof(ApiResponse<MerchantContractDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<MerchantContractDto>> UpdateContractStatus(
        long merchantId,
        long contractId,
        [FromBody] UpdateMerchantContractStatusCommand body,
        CancellationToken cancellationToken)
    {
        // 1. 绑定商户与合同标识
        var command = body with { MerchantId = merchantId, ContractId = contractId };

        // 2. 更新合同状态
        var result = await mediator.Send(command, cancellationToken);
        return ApiResponse<MerchantContractDto>.Ok(result);
    }

    /// <summary>
    /// 审核商户（通过/驳回）。
    /// </summary>
    /// <returns>审核后的商户信息。</returns>
    [HttpPost("{merchantId:long}/review")]
    [PermissionAuthorize("merchant:review")]
    [ProducesResponseType(typeof(ApiResponse<MerchantDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<MerchantDto>> Review(long merchantId, [FromBody] ReviewMerchantCommand body, CancellationToken cancellationToken)
    {
        // 1. 绑定商户标识
        var command = body with { MerchantId = merchantId };

        // 2. 执行审核
        var result = await mediator.Send(command, cancellationToken);
        return ApiResponse<MerchantDto>.Ok(result);
    }

    /// <summary>
    /// 审核日志。
    /// </summary>
    /// <returns>商户审核日志分页结果。</returns>
    [HttpGet("{merchantId:long}/audits")]
    [PermissionAuthorize("merchant:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<MerchantAuditLogDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<MerchantAuditLogDto>>> AuditLogs(
        long merchantId,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        CancellationToken cancellationToken = default)
    {
        // 1. 查询审核日志
        var result = await mediator.Send(new GetMerchantAuditLogsQuery(merchantId, page, pageSize), cancellationToken);

        // 2. 返回日志分页
        return ApiResponse<PagedResult<MerchantAuditLogDto>>.Ok(result);
    }

    /// <summary>
    /// 可选商户类目列表。
    /// </summary>
    /// <returns>可选的商户类目列表。</returns>
    [HttpGet("categories")]
    [PermissionAuthorize("merchant:read")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<string>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<IReadOnlyList<string>>> Categories(CancellationToken cancellationToken)
    {
        // 1. 查询可选类目
        var result = await mediator.Send(new GetMerchantCategoriesQuery(), cancellationToken);

        // 2. 返回类目列表
        return ApiResponse<IReadOnlyList<string>>.Ok(result);
    }
}
