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

namespace Meezi.API.Controllers;

[Route("api/cafes/{cafeId}/support/tickets")]
public class SupportTicketsController : CafeApiControllerBase
{
    private readonly ISupportTicketService _tickets;

    public SupportTicketsController(ISupportTicketService tickets)
    {
        _tickets = tickets;
    }

    [HttpGet]
    public async Task<IActionResult> List(string cafeId, ITenantContext tenant, CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var list = await _tickets.ListForCafeAsync(cafeId, cancellationToken);
        return Ok(new ApiResponse<object>(true, list));
    }

    [HttpGet("{ticketId}")]
    public async Task<IActionResult> Get(
        string cafeId,
        string ticketId,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var detail = await _tickets.GetForCafeAsync(cafeId, ticketId, cancellationToken);
        if (detail is null)
            return NotFoundError("Ticket not found.");

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

    [HttpPost]
    public async Task<IActionResult> Create(
        string cafeId,
        [FromBody] CreateSupportTicketRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (string.IsNullOrEmpty(tenant.UserId))
            return StatusCode(403, new ApiResponse<object>(false, null, new ApiError("FORBIDDEN", "User required.")));

        var detail = await _tickets.CreateForCafeAsync(cafeId, tenant.UserId, request, cancellationToken);
        return Ok(new ApiResponse<object>(true, detail));
    }

    [HttpPost("{ticketId}/messages")]
    public async Task<IActionResult> Reply(
        string cafeId,
        string ticketId,
        [FromBody] ReplySupportTicketRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (string.IsNullOrEmpty(tenant.UserId))
            return StatusCode(403, new ApiResponse<object>(false, null, new ApiError("FORBIDDEN", "User required.")));

        var existing = await _tickets.GetForCafeAsync(cafeId, ticketId, cancellationToken);
        if (existing is null)
            return NotFoundError("Ticket not found.");
        if (existing.Ticket.Status is Core.Enums.SupportTicketStatus.Closed
            or Core.Enums.SupportTicketStatus.Resolved)
            return BadRequest(new ApiResponse<object>(false, null,
                new ApiError("TICKET_CLOSED", "This ticket is closed and cannot receive new messages.")));

        var detail = await _tickets.ReplyAsMerchantAsync(cafeId, ticketId, tenant.UserId, request, cancellationToken);
        if (detail is null)
            return NotFoundError("Ticket not found.");

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