using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;

namespace Aberwyn.Controllers
{
    [ApiController]
    [Route("api/setup")]
    public class SetupApiController : ControllerBase
    {
        [HttpPost("testdb")]
        public IActionResult TestDbConnection([FromBody] DbTestRequest request)
        {
            try
            {
                var builder = new MySqlConnectionStringBuilder
                {
                    Server = request.Host,
                    Port = uint.Parse(request.Port),
                    UserID = request.User,
                    Password = request.Pass,
                    Database = "information_schema"
                };

                using (var conn = new MySqlConnection(builder.ConnectionString))
                {
                    conn.Open();

                    // Kontrollera om databasen redan finns
                    var checkCmd = new MySqlCommand("SELECT SCHEMA_NAME FROM SCHEMATA WHERE SCHEMA_NAME = @dbName", conn);
                    checkCmd.Parameters.AddWithValue("@dbName", request.Db);
                    var exists = checkCmd.ExecuteScalar();

                    if (exists != null)
                    {
                        return Ok(new
                        {
                            success = true,
                            message = "Anslutning OK och databasen finns redan."
                        });
                    }

                    // Testa skapa en temporär databas
                    var testDbName = $"testcheck_{Guid.NewGuid():N}".Substring(0, 12);
                    var createCmd = new MySqlCommand($"CREATE DATABASE `{testDbName}`", conn);
                    createCmd.ExecuteNonQuery();

                    var dropCmd = new MySqlCommand($"DROP DATABASE `{testDbName}`", conn);
                    dropCmd.ExecuteNonQuery();

                    return Ok(new
                    {
                        success = true,
                        message = "Anslutning OK. Databasen finns inte, men CREATE DATABASE är tillåten."
                    });
                }
            }
            catch (Exception ex)
            {
                return Ok(new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }



        public class DbTestRequest
        {
            public string Host { get; set; }
            public string Port { get; set; }
            public string Db { get; set; }
            public string User { get; set; }
            public string Pass { get; set; }
        }
    }
}
