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

namespace LittleShop.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = "Bearer")]
public class CustomersController : ControllerBase
{
    private readonly ICustomerService _customerService;
    private readonly ILogger<CustomersController> _logger;

    public CustomersController(ICustomerService customerService, ILogger<CustomersController> logger)
    {
        _customerService = customerService;
        _logger = logger;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<CustomerDto>>> GetCustomers([FromQuery] string? search = null)
    {
        if (!string.IsNullOrEmpty(search))
        {
            var searchResults = await _customerService.SearchCustomersAsync(search);
            return Ok(searchResults);
        }

        var customers = await _customerService.GetAllCustomersAsync();
        return Ok(customers);
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<CustomerDto>> GetCustomer(Guid id)
    {
        var customer = await _customerService.GetCustomerByIdAsync(id);
        if (customer == null)
        {
            return NotFound("Customer not found");
        }

        return Ok(customer);
    }

    [HttpGet("by-telegram/{telegramUserId}")]
    public async Task<ActionResult<CustomerDto>> GetCustomerByTelegramId(long telegramUserId)
    {
        var customer = await _customerService.GetCustomerByTelegramUserIdAsync(telegramUserId);
        if (customer == null)
        {
            return NotFound("Customer not found");
        }

        return Ok(customer);
    }

    [HttpPost]
    public async Task<ActionResult<CustomerDto>> CreateCustomer([FromBody] CreateCustomerDto createCustomerDto)
    {
        try
        {
            var customer = await _customerService.CreateCustomerAsync(createCustomerDto);
            return CreatedAtAction(nameof(GetCustomer), new { id = customer.Id }, customer);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    [HttpPost("get-or-create")]
    [AllowAnonymous] // Allow TeleBot to create customers
    public async Task<ActionResult<CustomerDto>> GetOrCreateCustomer([FromBody] CreateCustomerDto createCustomerDto)
    {
        var customer = await _customerService.GetOrCreateCustomerAsync(
            createCustomerDto.TelegramUserId,
            createCustomerDto.TelegramDisplayName,
            createCustomerDto.TelegramUsername,
            createCustomerDto.TelegramFirstName,
            createCustomerDto.TelegramLastName);

        if (customer == null)
        {
            return BadRequest("Failed to create customer");
        }

        return Ok(customer);
    }

    [HttpPut("{id}")]
    public async Task<ActionResult<CustomerDto>> UpdateCustomer(Guid id, [FromBody] UpdateCustomerDto updateCustomerDto)
    {
        var customer = await _customerService.UpdateCustomerAsync(id, updateCustomerDto);
        if (customer == null)
        {
            return NotFound("Customer not found");
        }

        return Ok(customer);
    }

    [HttpPost("{id}/block")]
    public async Task<ActionResult> BlockCustomer(Guid id, [FromBody] string reason)
    {
        var success = await _customerService.BlockCustomerAsync(id, reason);
        if (!success)
        {
            return NotFound("Customer not found");
        }

        return Ok(new { message = "Customer blocked successfully" });
    }

    [HttpPost("{id}/unblock")]
    public async Task<ActionResult> UnblockCustomer(Guid id)
    {
        var success = await _customerService.UnblockCustomerAsync(id);
        if (!success)
        {
            return NotFound("Customer not found");
        }

        return Ok(new { message = "Customer unblocked successfully" });
    }

    [HttpDelete("{id}")]
    public async Task<ActionResult> DeleteCustomer(Guid id)
    {
        var success = await _customerService.DeleteCustomerAsync(id);
        if (!success)
        {
            return NotFound("Customer not found");
        }

        return Ok(new { message = "Customer marked for deletion" });
    }
}