require "kemal"
require "./dns_manager"

module ContainerMom
  VERSION = "0.1.0"

  # Initialize DNS manager
  dns = DnsManager.instance

  # Set up Kemal routes
  post "/domains" do |env|
    begin
      request = JSON.parse(env.request.body.not_nil!)
      name = request["name"].as_s
      namespace = request["namespace"].as_s
      
      # Parse spec into ContainerDeploymentSpec
      spec = ContainerMom::Types::ContainerDeploymentSpec.from_json(request["spec"].to_json)

      dns.setup_domain(name, namespace, spec)
      
      env.response.content_type = "application/json"
      {status: "success", message: "Domain setup initiated"}.to_json
    rescue ex : JSON::ParseException
      env.response.status_code = 400
      {status: "error", message: "Invalid JSON payload"}.to_json
    rescue ex : DnsManager::Error
      env.response.status_code = 400
      {status: "error", message: ex.message}.to_json
    rescue ex
      env.response.status_code = 500
      {status: "error", message: "Internal server error"}.to_json
    end
  end

  get "/health" do |env|
    env.response.content_type = "application/json"
    {
      status: "healthy",
      version: VERSION
    }.to_json
  end

  # Start the server
  Kemal.run do |config|
    server = config.server.not_nil!
    server.bind_tcp "0.0.0.0", 8081
  end
end
