#!/bin/bash

MARIADB_BIN=/nix/store/a4jsa8kjdn3wlccj2wkvhxqza38rpxzf-mariadb-server-10.11.13/bin
DATADIR=/home/runner/mysql-data
SOCKET=/tmp/mysql.sock
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "==> Starting MariaDB..."
mkdir -p "$DATADIR"

pkill mariadbd 2>/dev/null || true
sleep 1

$MARIADB_BIN/mariadbd \
  --datadir="$DATADIR" \
  --socket="$SOCKET" \
  --port=3306 \
  --skip-grant-tables \
  --skip-networking=0 \
  --bind-address=127.0.0.1 \
  2>/tmp/mysql.log &

echo "==> Waiting for MariaDB to start..."
for i in $(seq 1 20); do
  if $MARIADB_BIN/mysql --socket="$SOCKET" -u root -e "SELECT 1;" &>/dev/null 2>&1; then
    echo "==> MariaDB ready"
    break
  fi
  sleep 1
done

# Create database if needed
$MARIADB_BIN/mysql --socket="$SOCKET" -u root -e \
  "CREATE DATABASE IF NOT EXISTS whatscrm CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null || true

# Import schema if tables are missing
TABLE_COUNT=$($MARIADB_BIN/mysql --socket="$SOCKET" -u root whatscrm -e "SHOW TABLES;" 2>/dev/null | wc -l)
if [ "$TABLE_COUNT" -lt 5 ]; then
  echo "==> Importing database schema..."
  $MARIADB_BIN/mysql --socket="$SOCKET" -u root whatscrm < "$SCRIPT_DIR/database/import.sql" 2>/dev/null || true
  echo "==> Schema imported"
fi

echo "==> Starting WhatsCRM on port ${PORT:-8080}..."
cd "$SCRIPT_DIR"
exec node server.js
