using Microsoft.AspNetCore.Mvc;
using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json.Linq;

namespace LittleShop.Controllers;

[ApiController]
[Route("api/btcpay-test")]
[Authorize(AuthenticationSchemes = "Cookies", Roles = "Admin")]
public class BTCPayTestController : ControllerBase
{
    private readonly IConfiguration _configuration;

    public BTCPayTestController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [HttpGet("connection")]
    public async Task<IActionResult> TestConnection()
    {
        try
        {
            var baseUrl = _configuration["BTCPayServer:BaseUrl"];
            var apiKey = _configuration["BTCPayServer:ApiKey"];
            
            if (string.IsNullOrEmpty(baseUrl) || string.IsNullOrEmpty(apiKey))
            {
                return BadRequest(new { error = "BTCPay Server configuration missing" });
            }

            // Create HttpClient with certificate bypass for internal networks
            var httpClient = new HttpClient(new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
            });
            
            var client = new BTCPayServerClient(new Uri(baseUrl), apiKey, httpClient);
            
            // Test basic connection by getting server info
            var serverInfo = await client.GetServerInfo();
            
            return Ok(new 
            { 
                status = "Connected",
                baseUrl = baseUrl,
                serverVersion = serverInfo?.Version,
                supportedPaymentMethods = serverInfo?.SupportedPaymentMethods,
                message = "BTCPay Server connection successful"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new 
            { 
                error = ex.Message,
                type = ex.GetType().Name,
                baseUrl = _configuration["BTCPayServer:BaseUrl"]
            });
        }
    }

    [HttpGet("stores")]
    public async Task<IActionResult> GetStores()
    {
        try
        {
            var baseUrl = _configuration["BTCPayServer:BaseUrl"];
            var apiKey = _configuration["BTCPayServer:ApiKey"];
            
            // Create HttpClient with certificate bypass for internal networks
            var httpClient = new HttpClient(new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
            });
            
            var client = new BTCPayServerClient(new Uri(baseUrl), apiKey, httpClient);
            
            // Get available stores
            var stores = await client.GetStores();
            
            return Ok(new 
            { 
                stores = stores.Select(s => new 
                {
                    id = s.Id,
                    name = s.Name,
                    website = s.Website,
                    defaultCurrency = s.DefaultCurrency
                }).ToList(),
                message = "Stores retrieved successfully"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new 
            { 
                error = ex.Message,
                type = ex.GetType().Name
            });
        }
    }

    [HttpPost("test-invoice")]
    public async Task<IActionResult> CreateTestInvoice([FromBody] TestInvoiceRequest request)
    {
        try
        {
            var baseUrl = _configuration["BTCPayServer:BaseUrl"];
            var apiKey = _configuration["BTCPayServer:ApiKey"];
            var storeId = _configuration["BTCPayServer:StoreId"];
            
            if (string.IsNullOrEmpty(storeId))
            {
                return BadRequest(new { error = "Store ID not configured" });
            }

            // Create HttpClient with certificate bypass for internal networks
            var httpClient = new HttpClient(new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
            });
            
            var client = new BTCPayServerClient(new Uri(baseUrl), apiKey, httpClient);
            
            // Create test invoice
            var invoiceRequest = new CreateInvoiceRequest
            {
                Amount = request.Amount,
                Currency = request.Currency ?? "GBP",
                Metadata = JObject.FromObject(new 
                {
                    orderId = $"test-{Guid.NewGuid()}",
                    source = "LittleShop-Test"
                })
            };

            var invoice = await client.CreateInvoice(storeId, invoiceRequest);
            
            return Ok(new 
            { 
                status = "Invoice Created",
                invoiceId = invoice.Id,
                amount = invoice.Amount,
                currency = invoice.Currency,
                checkoutLink = invoice.CheckoutLink,
                expiresAt = invoice.ExpirationTime,
                message = "Test invoice created successfully"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new 
            { 
                error = ex.Message,
                type = ex.GetType().Name
            });
        }
    }
}

public class TestInvoiceRequest
{
    public decimal Amount { get; set; } = 0.01m;
    public string? Currency { get; set; } = "GBP";
}