using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using LittleShop.DTOs;
using LittleShop.Services;
using System.Security.Claims;

namespace LittleShop.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize(Policy = "AdminOnly")]
public class MessagesController : ControllerBase
{
    private readonly ICustomerMessageService _messageService;
    private readonly ILogger<MessagesController> _logger;

    public MessagesController(ICustomerMessageService messageService, ILogger<MessagesController> logger)
    {
        _messageService = messageService;
        _logger = logger;
    }

    [HttpPost]
    public async Task<ActionResult<CustomerMessageDto>> SendMessage([FromBody] CreateCustomerMessageDto createMessageDto)
    {
        try
        {
            // Always set AdminUserId to null to avoid FK constraint issues for now
            createMessageDto.AdminUserId = null;
            
            // Validate that CustomerId exists
            var customerExists = await _messageService.ValidateCustomerExistsAsync(createMessageDto.CustomerId);
            if (!customerExists)
            {
                return BadRequest($"Customer {createMessageDto.CustomerId} does not exist");
            }
            
            // If OrderId is provided, validate it belongs to the customer
            if (createMessageDto.OrderId.HasValue)
            {
                var orderBelongsToCustomer = await _messageService.ValidateOrderBelongsToCustomerAsync(
                    createMessageDto.OrderId.Value, 
                    createMessageDto.CustomerId);
                    
                if (!orderBelongsToCustomer)
                {
                    return BadRequest("Order does not belong to the specified customer");
                }
            }

            var message = await _messageService.CreateMessageAsync(createMessageDto);
            if (message == null)
            {
                return BadRequest("Failed to create message");
            }

            return Ok(message); // Use Ok instead of CreatedAtAction to avoid routing issues
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error creating customer message");
            return BadRequest($"Error creating message: {ex.Message}");
        }
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<CustomerMessageDto>> GetMessage(Guid id)
    {
        var message = await _messageService.GetMessageByIdAsync(id);
        if (message == null)
        {
            return NotFound("Message not found");
        }

        return Ok(message);
    }

    [HttpGet("customer/{customerId}")]
    public async Task<ActionResult<IEnumerable<CustomerMessageDto>>> GetCustomerMessages(Guid customerId)
    {
        var messages = await _messageService.GetCustomerMessagesAsync(customerId);
        return Ok(messages);
    }

    [HttpGet("order/{orderId}")]
    public async Task<ActionResult<IEnumerable<CustomerMessageDto>>> GetOrderMessages(Guid orderId)
    {
        var messages = await _messageService.GetOrderMessagesAsync(orderId);
        return Ok(messages);
    }

    [HttpGet("pending")]
    [AllowAnonymous] // Allow bots to access without authentication
    public async Task<ActionResult<IEnumerable<CustomerMessageDto>>> GetPendingMessages([FromQuery] string platform = "Telegram")
    {
        var messages = await _messageService.GetPendingMessagesAsync(platform);
        return Ok(messages);
    }

    [HttpPost("{id}/mark-sent")]
    [AllowAnonymous] // Allow bots to access without authentication
    public async Task<ActionResult> MarkMessageAsSent(Guid id, [FromQuery] string? platformMessageId = null)
    {
        var success = await _messageService.MarkMessageAsSentAsync(id, platformMessageId);
        if (!success)
        {
            return NotFound("Message not found");
        }

        return Ok();
    }

    [HttpPost("{id}/mark-delivered")]
    public async Task<ActionResult> MarkMessageAsDelivered(Guid id)
    {
        var success = await _messageService.MarkMessageAsDeliveredAsync(id);
        if (!success)
        {
            return NotFound("Message not found");
        }

        return Ok();
    }

    [HttpPost("{id}/mark-failed")]
    [AllowAnonymous] // Allow bots to access without authentication
    public async Task<ActionResult> MarkMessageAsFailed(Guid id, [FromBody] string reason)
    {
        var success = await _messageService.MarkMessageAsFailedAsync(id, reason);
        if (!success)
        {
            return NotFound("Message not found");
        }

        return Ok();
    }
}