using Microsoft.AspNetCore.Mvc;
using LittleShop.DTOs;
using LittleShop.Services;
using LittleShop.Models;

namespace LittleShop.Controllers;

[ApiController]
[Route("api/bot/messages")]
public class BotMessagesController : ControllerBase
{
    private readonly ICustomerMessageService _messageService;
    private readonly ILogger<BotMessagesController> _logger;

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

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

    [HttpPost("{id}/mark-sent")]
    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-failed")]
    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();
    }

    // TEMPORARY TEST ENDPOINT - REMOVE IN PRODUCTION
    [HttpPost("test-create")]
    public async Task<ActionResult<CustomerMessageDto>> CreateTestMessage([FromBody] CreateTestMessageDto dto)
    {
        var createMessageDto = new CreateCustomerMessageDto
        {
            CustomerId = dto.CustomerId,
            OrderId = dto.OrderId,
            Type = dto.Type,
            Subject = dto.Subject,
            Content = dto.Content,
            Priority = dto.Priority,
            IsUrgent = dto.IsUrgent
        };

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

        return Ok(message);
    }
    
    [HttpPost("customer-create")]
    public async Task<ActionResult> CreateCustomerMessage([FromBody] CreateCustomerMessageFromTelegramDto dto)
    {
        try
        {
            // Create CustomerToAdmin message directly
            var message = new CustomerMessage
            {
                Id = Guid.NewGuid(),
                CustomerId = dto.CustomerId,
                OrderId = dto.OrderId,
                Direction = MessageDirection.CustomerToAdmin,
                Type = dto.Type,
                Subject = dto.Subject,
                Content = dto.Content,
                Status = MessageStatus.Read, // Customer messages are immediately "read" by system
                Platform = "Telegram",
                Priority = dto.Priority,
                IsUrgent = dto.IsUrgent,
                CreatedAt = DateTime.UtcNow,
                ThreadId = Guid.NewGuid() // Will be updated if part of existing thread
            };

            // Save directly to database (bypass the regular CreateMessageAsync which is for AdminToCustomer)
            var result = await _messageService.CreateCustomerToAdminMessageAsync(message);
            if (!result)
            {
                return BadRequest("Failed to create customer message");
            }

            return Ok();
        }
        catch (Exception ex)
        {
            return BadRequest($"Error creating customer message: {ex.Message}");
        }
    }

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

// TEMPORARY DTO FOR TESTING
public class CreateTestMessageDto
{
    public Guid CustomerId { get; set; }
    public Guid? OrderId { get; set; }
    public MessageType Type { get; set; }
    public string Subject { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
    public int Priority { get; set; } = 5;
    public bool IsUrgent { get; set; } = false;
}

// DTO for customer messages from Telegram
public class CreateCustomerMessageFromTelegramDto
{
    public Guid CustomerId { get; set; }
    public Guid? OrderId { get; set; }
    public MessageType Type { get; set; }
    public string Subject { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
    public int Priority { get; set; } = 5;
    public bool IsUrgent { get; set; } = false;
}