#!/bin/bash
# =============================================================================
# officer-setup — schema and build
# =============================================================================
#
# Definitions only.
#
# Both run AS the owner, from the repo. Neither is idempotent in the sense of
# "does nothing the second time" — both are safe to repeat, which is not the same
# thing and is the property that matters for a script people re-run.

[[ -n "${OFFICER_SETUP_BUILD_LOADED:-}" ]] && return 0
OFFICER_SETUP_BUILD_LOADED=1

# `bun db:push` — drizzle-kit diffs the schema code against the live database.
#
# No migrations here and no __drizzle_migrations table: the schema code IS the
# source of truth (src/databases/CLAUDE.md). On the empty database section 5 just
# created there is nothing to drop, so the prompt drizzle-kit shows for a
# destructive change cannot appear.
#
# It can still appear on a RE-RUN against a database with data, and a prompt
# nobody sees would hang the script forever — so stdin is closed rather than left
# attached. drizzle-kit then fails instead of waiting, which is the outcome you
# want at 3am.
push_schema() {
  sudo -u "$USERNAME" bash -c "cd '$(platform_dir)' && bun db:push </dev/null" 2>&1
}

# What tables the schema will create, read from the aggregator rather than
# guessed. This is what makes the section able to say what it is about to do.
schema_table_count() {
  local dir
  dir="$(platform_dir)/src/databases/officer_db/src"
  grep -oP "^export \* from '\./\K[\w-]+(?=/schema')" "$dir/schema.ts" 2>/dev/null | while read -r f; do
    grep -c "pgTable(" "$dir/$f/schema.ts" 2>/dev/null || true
  done | awk '{s+=$1} END {print s+0}'
}

# `bun gen:index` — substitutes PUBLIC_URL into index.html and writes
# index.gen.html, which is what the server actually imports.
#
# Not optional and not cosmetic: without it the server has no page to serve. It
# is gitignored, so a fresh clone never has one.
gen_index() {
  sudo -u "$USERNAME" bash -c "cd '$(platform_dir)' && bun gen:index '$ENV_PUBLIC_URL'" 2>&1
}

gen_index_output() { echo "$(platform_dir)/src/apps/officer-web/index.gen.html"; }
