#!/usr/bin/env bash
# Step 07: Install PostgreSQL 15 in WSL Ubuntu.
# Mirrors the exact commands from the cloud-setup skill.

step_name="Install PostgreSQL 15 (WSL)"

run() {
  log_info "Adding PostgreSQL apt repository..."
  vm_exec wsl "CODENAME=\$(lsb_release -cs) && sudo sh -c \"echo 'deb http://apt.postgresql.org/pub/repos/apt/ \${CODENAME}-pgdg main' > /etc/apt/sources.list.d/pgdg.list\"" --timeout 60

  log_info "Importing PostgreSQL signing key..."
  vm_exec wsl "wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -" --timeout 60

  log_info "Updating apt and installing PostgreSQL 15..."
  vm_exec wsl "sudo apt-get update -qq && sudo apt-get install -y postgresql-15" --timeout "$TIMEOUT_INSTALL"

  log_info "Starting PostgreSQL service..."
  vm_exec wsl "sudo service postgresql start" --timeout 30

  log_info "Setting postgres password..."
  vm_exec wsl "sudo -u postgres psql -c \"ALTER USER postgres PASSWORD 'postgres_admin_password';\"" --timeout 30

  log_info "Creating localv1db database..."
  vm_exec wsl "sudo -u postgres createdb localv1db" --timeout 30
}

verify() {
  # Check pg_isready
  local ready
  ready=$(vm_exec wsl "pg_isready" 2>/dev/null || echo "")
  if ! echo "$ready" | grep -q "accepting connections"; then
    log_fail "PostgreSQL not accepting connections"
    return 1
  fi
  log_pass "PostgreSQL accepting connections"

  # Check localv1db exists
  local dbs
  dbs=$(vm_exec wsl "sudo -u postgres psql -lqt" 2>/dev/null || echo "")
  if echo "$dbs" | grep -q "localv1db"; then
    log_pass "Database 'localv1db' exists"
    return 0
  fi
  log_fail "Database 'localv1db' not found"
  return 1
}
