#!/bin/bash
set -e

# Attendre que le service docuseal soit prêt
until curl -s http://docuseal:3000 > /dev/null; do
  echo "Waiting for docuseal to be ready..."
  sleep 5
done

encrypt_password() {
  local password=$1
  ruby -e "require 'bcrypt'; puts BCrypt::Password.create('$password')"
}

# Mot de passe encrypté
ENCRYPTED_PASSWORD=$(encrypt_password "$USER_PASSWORD")

# Insérer les données dans les tables accounts et users si elles n'existent pas déjà
PGPASSWORD=$POSTGRES_PASSWORD psql -v ON_ERROR_STOP=1 --host=database --port=5432 --username="$POSTGRES_USER" --dbname=docuseal <<-EOSQL
    -- Vérifier l'existence du compte
    DO \$\$
    BEGIN
        IF NOT EXISTS (SELECT 1 FROM accounts WHERE name = '$USER_COMPANY') THEN
            -- Insérer dans la table accounts
            INSERT INTO accounts (name, timezone, locale, created_at, updated_at, uuid) VALUES
            ('$USER_COMPANY', 'UTC', 'en', NOW(), NOW(), gen_random_uuid());
        END IF;
    END
    \$\$;

    -- Vérifier l'existence de l'utilisateur
    DO \$\$
    BEGIN
        IF NOT EXISTS (SELECT 1 FROM users WHERE email = '$USER_EMAIL') THEN
            -- Insérer dans la table users
            INSERT INTO users (first_name, last_name, email, encrypted_password, account_id, role, sign_in_count, failed_attempts, created_at, updated_at, uuid, otp_required_for_login) VALUES
            ('$USER_FIRST_NAME', '$USER_LAST_NAME', '$USER_EMAIL', '$ENCRYPTED_PASSWORD', (SELECT id FROM accounts WHERE name = '$USER_COMPANY'), 'admin', 1, 0, NOW(), NOW(), gen_random_uuid(), false);
        END IF;
    END
    \$\$;
EOSQL