# frozen_string_literal: false

# ----------------------------------------------------------------------------
#
#     ***     AUTO GENERATED CODE    ***    Type: MMv1     ***
#
# ----------------------------------------------------------------------------
#
#     This file is automatically generated by Magic Modules and manual
#     changes will be clobbered when the file is regenerated.
#
#     Please read more about how to change this file in README.md and
#     CONTRIBUTING.md located at the root of this package.
#
# ----------------------------------------------------------------------------
require 'gcp_backend'
require 'google/sql/property/connect_ip_addresses'
require 'google/sql/property/connect_server_ca_cert'

# A provider to manage Cloud SQL resources.
class SQLConnect < GcpResourceBase
  name 'google_sql_connect'
  desc 'Connect'
  supports platform: 'gcp'

  attr_reader :params
  attr_reader :region
  attr_reader :ip_addresses
  attr_reader :database_version
  attr_reader :backend_type
  attr_reader :server_ca_cert
  attr_reader :instance

  def initialize(params)
    super(params.merge({ use_http_transport: true }))
    @params = params
    @fetched = @connection.fetch(product_url(params[:beta]), resource_base_url, params, 'Get')
    parse unless @fetched.nil?
  end

  def parse
    @region = @fetched['region']
    @ip_addresses = GoogleInSpec::SQL::Property::ConnectIpAddressesArray.parse(@fetched['ipAddresses'], to_s)
    @database_version = @fetched['databaseVersion']
    @backend_type = @fetched['backendType']
    @server_ca_cert = GoogleInSpec::SQL::Property::ConnectServerCaCert.new(@fetched['serverCaCert'], to_s)
    @instance = @fetched['instance']
  end

  def exists?
    !@fetched.nil?
  end

  def to_s
    "Connect #{@params[:name]}"
  end

  private

  def product_url(_ = nil)
    'https://sqladmin.googleapis.com/sql/v1beta4/'
  end

  def resource_base_url
    'projects/{{project}}/instances/{{instance}}/connectSettings'
  end
end
