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

if ! command -v tmux >/dev/null 2>&1; then
  echo "tmux is required but was not found in PATH." >&2
  exit 1
fi

repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
session_name="trakqr"

if [[ -n "${TMUX-}" ]]; then
  current_session=$(tmux display-message -p "#S")
  tmux new-window -t "${current_session}" -n api "cd \"${repo_root}\" && dotnet run --project src/api"
  tmux new-window -t "${current_session}" -n frontend "cd \"${repo_root}\"/src/frontend && npm run dev"
  tmux select-window -t "${current_session}:api"
  echo "Added windows 'api' and 'frontend' to session '${current_session}'."
  exit 0
fi

if tmux has-session -t "${session_name}" 2>/dev/null; then
  echo "Session '${session_name}' already exists. Attaching..."
  tmux attach -t "${session_name}"
  exit 0
fi

tmux new-session -d -s "${session_name}" -n api "cd \"${repo_root}\" && dotnet watch --project src/api"
tmux new-window -t "${session_name}" -n frontend "cd \"${repo_root}\"/src/frontend && npm run dev"

tmux attach -t "${session_name}"
