#!/bin/bash

set -euo pipefail

# Caminhos
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
MIGRATIONS_FILE="${ROOT_DIR}/migrations/migrations_v1.sql"

# Carrega variáveis do .env se existir
if [[ -f "${ROOT_DIR}/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "${ROOT_DIR}/.env"
  set +a
fi

# Configurações de conexão (PostgreSQL)
DB_HOST=${DB_HOST:-localhost}
DB_PORT=${DB_PORT:-5432}
DB_NAME=${DB_NAME:-tooeasy}
DB_USER=${DB_USER:-postgres}
DB_PASSWORD=${DB_PASSWORD:-}

echo "[setup] Host=${DB_HOST} Port=${DB_PORT} DB=${DB_NAME} User=${DB_USER}"

if [[ ! -f "${MIGRATIONS_FILE}" ]]; then
  echo "[setup] ERRO: Arquivo de migração não encontrado: ${MIGRATIONS_FILE}" >&2
  exit 1
fi

# 1) Cria o banco de dados se não existir
echo "[setup] Verificando se o banco '${DB_NAME}' existe..."
if ! PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname='${DB_NAME}'" | grep -q 1; then
  echo "[setup] Criando banco de dados '${DB_NAME}'..."
  PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d postgres -c "CREATE DATABASE \"${DB_NAME}\";"
else
  echo "[setup] Banco '${DB_NAME}' já existe."
fi

# 2) Executa migração (schema) somente se ainda não existir
echo "[setup] Verificando schema..."
if [[ -z "$(PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -tAc "SELECT to_regclass('public.company')")" ]]; then
  echo "[setup] Aplicando migrações do arquivo: ${MIGRATIONS_FILE}"
  PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -v ON_ERROR_STOP=1 -f "${MIGRATIONS_FILE}"
else
  echo "[setup] Schema já existente. Pulando migrações."
fi

# 3) Seed inicial (idempotente)
echo "[setup] Inserindo dados iniciais (seed)..."

PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -v ON_ERROR_STOP=1 -c "
INSERT INTO \"company\" (company_name, company_flag)
SELECT 'LumyonTech', 'a'
WHERE NOT EXISTS (SELECT 1 FROM \"company\" WHERE company_name = 'LumyonTech');
"

PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -v ON_ERROR_STOP=1 -c "
INSERT INTO \"role\" (company_id, role_name, role_permission, role_flag)
SELECT c.company_id, 'Admin', '{}'::jsonb, 'a'
FROM \"company\" c
WHERE c.company_name = 'LumyonTech'
  AND NOT EXISTS (
    SELECT 1 FROM \"role\" r WHERE r.role_name = 'Admin' AND r.company_id = c.company_id
  );
"

PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -v ON_ERROR_STOP=1 -c "
INSERT INTO \"status\" (status_status)
SELECT 'OPEN'
WHERE NOT EXISTS (SELECT 1 FROM \"status\" WHERE status_status = 'OPEN');
"

PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -v ON_ERROR_STOP=1 -c "
INSERT INTO \"chain\" (chain_name)
SELECT 'polygon'
WHERE NOT EXISTS (SELECT 1 FROM \"chain\" WHERE chain_name = 'polygon');
"

# 4) Resumo
echo "[setup] Finalizado com sucesso!"
echo "[setup] Tabelas seed (amostra):"
PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -c "
TABLE \"company\";
TABLE \"role\";
TABLE \"status\";
TABLE \"chain\";
" | sed 's/\x1b\[[0-9;]*m//g'