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

namespace Meezi.Admin.API.Controllers;

[Route("api/admin/tickets")]
public class AdminTicketsController : AdminApiControllerBase
{
    private readonly ISupportTicketService _tickets;

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

    [HttpGet]
    public async Task<IActionResult> List([FromQuery] SupportTicketStatus? status, CancellationToken cancellationToken)
    {
        var list = await _tickets.ListAllAsync(status, cancellationToken);
        return Ok(new ApiResponse<object>(true, list));
    }

    [HttpGet("{ticketId}")]
    public async Task<IActionResult> Get(string ticketId, CancellationToken cancellationToken)
    {
        var detail = await _tickets.GetAdminAsync(ticketId, cancellationToken);
        if (detail is null)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Ticket not found.")));

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

    [HttpPost("{ticketId}/messages")]
    public async Task<IActionResult> Reply(
        string ticketId,
        [FromBody] ReplySupportTicketRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        var existing = await _tickets.GetAdminAsync(ticketId, cancellationToken);
        if (existing is null)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Ticket not found.")));
        if (existing.Ticket.Status is SupportTicketStatus.Closed)
            return BadRequest(new ApiResponse<object>(false, null,
                new ApiError("TICKET_CLOSED", "This ticket is closed.")));

        var adminId = RequireAdminId(tenant);
        var detail = await _tickets.ReplyAsAdminAsync(ticketId, adminId, request, cancellationToken);
        if (detail is null)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Ticket not found.")));

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

    [HttpPatch("{ticketId}")]
    public async Task<IActionResult> Update(
        string ticketId,
        [FromBody] UpdateSupportTicketRequest request,
        CancellationToken cancellationToken)
    {
        var detail = await _tickets.UpdateAdminAsync(ticketId, request, cancellationToken);
        if (detail is null)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Ticket not found.")));

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