-- TYAPI Server Database Initialization Script
-- This script runs when PostgreSQL container starts for the first time

-- Create development database if it doesn't exist
CREATE DATABASE tyapi_dev;

-- Create test database for running tests
CREATE DATABASE tyapi_test;

-- Create production database (for reference)
-- CREATE DATABASE tyapi_prod;

-- Connect to development database
\c tyapi_dev;

-- Enable necessary extensions
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE EXTENSION IF NOT EXISTS "pg_trgm";

CREATE EXTENSION IF NOT EXISTS "btree_gin";

-- Create schemas for better organization
CREATE SCHEMA IF NOT EXISTS public;

CREATE SCHEMA IF NOT EXISTS logs;

CREATE SCHEMA IF NOT EXISTS metrics;

-- Set search path
SET search_path TO public, logs, metrics;

-- Connect to test database and setup extensions
\c tyapi_test;

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE EXTENSION IF NOT EXISTS "pg_trgm";

CREATE EXTENSION IF NOT EXISTS "btree_gin";

CREATE SCHEMA IF NOT EXISTS public;

CREATE SCHEMA IF NOT EXISTS logs;

CREATE SCHEMA IF NOT EXISTS metrics;

SET search_path TO public, logs, metrics;

-- Switch back to development database
\c tyapi_dev;

-- Create application-specific roles (optional)
-- CREATE ROLE tyapi_app WITH LOGIN PASSWORD 'app_password';
-- CREATE ROLE tyapi_readonly WITH LOGIN PASSWORD 'readonly_password';

-- Grant permissions
-- GRANT CONNECT ON DATABASE tyapi_dev TO tyapi_app;
-- GRANT USAGE ON SCHEMA public TO tyapi_app;
-- GRANT CREATE ON SCHEMA public TO tyapi_app;

-- Initial seed data can be added here
-- This will be replaced by proper migrations in the application

-- Log the initialization
INSERT INTO
    pg_stat_statements_info (dealloc)
VALUES (0) ON CONFLICT DO NOTHING;

-- Create a simple health check function
CREATE OR REPLACE FUNCTION health_check()
RETURNS json AS $$
BEGIN
    RETURN json_build_object(
        'status', 'healthy',
        'database', current_database(),
        'timestamp', now(),
        'version', version()
    );
END;
$$ LANGUAGE plpgsql;