#!/usr/bin/env bash
set -euo pipefail

MYSQL_ROOT_USER="${MYSQL_ROOT_USER:-root}"
MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-}"
MYSQL_HOST="${MYSQL_HOST:-127.0.0.1}"
MYSQL_PORT="${MYSQL_PORT:-3306}"
MYSQL_DATABASE="${MYSQL_DATABASE:-photobooth}"
MYSQL_APP_USER="${MYSQL_APP_USER:-photobooth_app}"
MYSQL_APP_PASSWORD="${MYSQL_APP_PASSWORD:-}"
MARKER_FILE="${MARKER_FILE:-/var/lib/photobooth/db-setup.done}"

if [ -z "$MYSQL_ROOT_PASSWORD" ]; then
  echo "MYSQL_ROOT_PASSWORD is required." >&2
  exit 1
fi

if [ -z "$MYSQL_APP_PASSWORD" ]; then
  echo "MYSQL_APP_PASSWORD is required." >&2
  exit 1
fi

if [ -f "$MARKER_FILE" ]; then
  echo "Database already initialized: $MARKER_FILE"
  exit 0
fi

mkdir -p "$(dirname "$MARKER_FILE")"

MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql \
  --protocol=TCP \
  -h "$MYSQL_HOST" \
  -P "$MYSQL_PORT" \
  -u "$MYSQL_ROOT_USER" <<SQL
CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\`
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_0900_ai_ci;

CREATE USER IF NOT EXISTS '$MYSQL_APP_USER'@'%' IDENTIFIED BY '$MYSQL_APP_PASSWORD';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX ON \`$MYSQL_DATABASE\`.* TO '$MYSQL_APP_USER'@'%';
FLUSH PRIVILEGES;

USE \`$MYSQL_DATABASE\`;

CREATE TABLE IF NOT EXISTS users (
  id CHAR(36) PRIMARY KEY,
  email VARCHAR(255) NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  name VARCHAR(120) NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS refresh_tokens (
  id CHAR(36) PRIMARY KEY,
  user_id CHAR(36) NOT NULL,
  token_hash VARCHAR(255) NOT NULL,
  expires_at DATETIME NOT NULL,
  revoked_at DATETIME NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uq_refresh_token_hash (token_hash),
  KEY idx_refresh_user (user_id),
  CONSTRAINT fk_refresh_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS media (
  id CHAR(36) PRIMARY KEY,
  user_id CHAR(36) NOT NULL,
  type ENUM('shot','strip') NOT NULL,
  url VARCHAR(2048) NOT NULL,
  thumb_url VARCHAR(2048) NULL,
  theme_id VARCHAR(64) NULL,
  meta JSON NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_media_user_created (user_id, created_at),
  KEY idx_media_type (type),
  CONSTRAINT fk_media_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;
SQL

touch "$MARKER_FILE"
echo "Database initialized."
