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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT_DIR"

echo "=== FitCRM Dev Setup ==="
echo ""

# 1. Start Docker services
echo "[1/4] Запуск PostgreSQL + Redis + coturn..."
docker compose up -d
echo "  Ожидание готовности PostgreSQL..."
until docker compose exec -T postgres pg_isready -U fitcrm -d fitcrm > /dev/null 2>&1; do
  sleep 1
done
echo "  PostgreSQL готов."
echo ""

# 2. Push Prisma schema (creates tables without migrations)
echo "[2/4] Применение Prisma-схемы (db push)..."
cd "$ROOT_DIR/apps/api"
npx prisma db push --skip-generate 2>&1 | tail -5
npx prisma generate 2>&1 | tail -3
echo ""

# 3. Apply RLS policies
echo "[3/4] Применение RLS-политик..."
if [ -f "prisma/migrations/00001_enable_rls/migration.sql" ]; then
  PGPASSWORD=fitcrm_dev_password psql -h localhost -U fitcrm -d fitcrm \
    -f prisma/migrations/00001_enable_rls/migration.sql 2>/dev/null || true
  echo "  RLS-политики применены."
else
  echo "  Файл RLS-миграции не найден, пропускаю."
fi
echo ""

# 4. Seed
echo "[4/4] Загрузка тестовых данных (seed)..."
if [ -f "prisma/seed.ts" ]; then
  npx ts-node prisma/seed.ts
else
  echo "  Файл seed.ts не найден, пропускаю."
fi
echo ""

echo "=== Готово! ==="
echo ""
echo "Запуск dev-серверов:"
echo "  cd $ROOT_DIR && pnpm dev"
echo ""
echo "Или по отдельности:"
echo "  pnpm --filter api dev          # API      → http://localhost:3000"
echo "  pnpm --filter web-admin dev    # Рецепция → http://localhost:3001"
echo "  pnpm --filter web-club-admin dev       # Клуб    → http://localhost:3002"
echo "  pnpm --filter web-platform-admin dev   # Платформа → http://localhost:3003"
echo ""
echo "Swagger: http://localhost:3000/api/docs"
echo ""
echo "Тестовые учётные записи:"
echo "  Суперадмин:  +70000000001 / admin123"
echo "  Админ клуба: +70000000002 / admin123"
echo "  Координатор: +70000000003 / admin123"
echo "  Рецепция:    +70000000004 / admin123"
echo "  Тренер 1:    +70000000010 / trainer123"
echo "  Тренер 2:    +70000000011 / trainer123"
echo "  Тренер 3:    +70000000012 / trainer123"
