-- PostgreSQL initialization script for Placebo.mk development
-- Creates separate databases for backend and CMS

-- Create databases if they don't exist
SELECT 'CREATE DATABASE placebo_backend_db'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'placebo_backend_db')\gexec

SELECT 'CREATE DATABASE placebo_cms_db'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'placebo_cms_db')\gexec

-- Create user if it doesn't exist
DO $$
BEGIN
  IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'placebo_user') THEN
    CREATE USER placebo_user WITH PASSWORD 'placebo_password';
  END IF;
END
$$;

-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE placebo_backend_db TO placebo_user;
GRANT ALL PRIVILEGES ON DATABASE placebo_cms_db TO placebo_user;

-- Create extensions (useful for some applications)
\c placebo_backend_db
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

\c placebo_cms_db  
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

-- Set search path for convenience
ALTER DATABASE placebo_backend_db SET search_path TO public;
ALTER DATABASE placebo_cms_db SET search_path TO public;

-- Output status
SELECT 'PostgreSQL initialization complete' AS status;
SELECT 
  datname as database,
  pg_size_pretty(pg_database_size(datname)) as size,
  (SELECT count(*) FROM pg_tables WHERE schemaname = 'public') as tables_count
FROM pg_database 
WHERE datname IN ('placebo_backend_db', 'placebo_cms_db');