#!/bin/bash
set -e

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
APP_PROPS="$ROOT_DIR/src/main/resources/application-postgres.properties"

if [ -f "$ROOT_DIR/.env" ]; then
  export $(grep -v '^#' "$ROOT_DIR/.env" | xargs)
fi

get_prop() {
  grep "^$1=" "$APP_PROPS" | cut -d'=' -f2 | sed 's/${[^:]*:\([^}]*\)}/\1/' | tr -d '\r'
}

DB_URL=$(get_prop "spring.datasource.url")
DB_USERNAME=$(get_prop "spring.datasource.username")
DB_PASSWORD=$(get_prop "spring.datasource.password")

DB_HOST=$(echo "$DB_URL" | sed -E 's|jdbc:postgresql://([^:/]+).*|\1|')
DB_PORT=$(echo "$DB_URL" | sed -E 's|jdbc:postgresql://[^:/]+:([0-9]+).*|\1|')
DB_NAME=$(echo "$DB_URL" | sed -E 's|.*/([^?]+)$|\1|')

DB_PORT=${DB_PORT:-5432}

INIT_SQL="$ROOT_DIR/src/main/resources/db/migration/postgresql/V1__init.sql"
SEED_SQL="$ROOT_DIR/src/main/resources/db/migration/postgresql/V2__seed_company_role.sql"

if ! command -v psql &> /dev/null; then
  echo "Erro: psql não encontrado. Instale o cliente PostgreSQL (psql)."
  exit 1
fi

DB_EXISTS=$(PGPASSWORD=$DB_PASSWORD psql -U "$DB_USERNAME" -h "$DB_HOST" -p "$DB_PORT" -d "postgres" -tAc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'")

if [ "$DB_EXISTS" != "1" ]; then
  echo "Criando banco de dados '$DB_NAME'..."
  PGPASSWORD=$DB_PASSWORD psql -U "$DB_USERNAME" -h "$DB_HOST" -p "$DB_PORT" -d "postgres" -c "CREATE DATABASE \"$DB_NAME\";"
else
  echo "Banco '$DB_NAME' já existe, prosseguindo..."
fi

echo "Executando migrations..."
PGPASSWORD=$DB_PASSWORD psql -U "$DB_USERNAME" -h "$DB_HOST" -p "$DB_PORT" -d "$DB_NAME" -f "$INIT_SQL"

echo "Executando seed..."
PGPASSWORD=$DB_PASSWORD psql -U "$DB_USERNAME" -h "$DB_HOST" -p "$DB_PORT" -d "$DB_NAME" -f "$SEED_SQL"

echo "Setup concluído com sucesso para o banco '$DB_NAME'."