-- One-time dev/prod database split on TrueNAS PostgreSQL.
--
-- Preferred: pgAdmin on dev PC — open db/split-dev-prod-pgadmin.sql (step-by-step).
-- Alternative (if psql is installed): psql -h 192.168.10.122 -U postgres -d postgres -f db/split-dev-prod.sql
--
-- NOTE: CREATE DATABASE cannot run inside a DO block; this file uses standalone statements.

-- Disconnect clients
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname IN ('Gallery', 'gallery', 'gallery_prod', 'gallery_dev')
  AND pid <> pg_backend_pid();

-- Rename legacy → gallery_prod (run ONE of these; comment out the other)
ALTER DATABASE "Gallery" RENAME TO gallery_prod;
-- ALTER DATABASE gallery RENAME TO gallery_prod;

-- Disconnect from prod before template clone
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'gallery_prod' AND pid <> pg_backend_pid();

-- Clone dev from prod (skip if gallery_dev already exists)
CREATE DATABASE gallery_dev WITH TEMPLATE gallery_prod;

GRANT ALL PRIVILEGES ON DATABASE gallery_dev TO gallery;
GRANT ALL PRIVILEGES ON DATABASE gallery_prod TO gallery;
