#!/bin/bash
#
# Database setup and configuration
#

setup_database() {
    log_info "Setting up database..."
    
    # Generate database password if not set
    if [[ -z "${CALYPSO_DB_PASSWORD:-}" ]]; then
        CALYPSO_DB_PASSWORD=$(generate_db_password)
        log_info "Generated database password"
    fi
    
    # Create database and user
    create_database_user
    
    # Run migrations
    run_migrations
    
    # Create default admin user
    create_default_admin
    
    log_info "✓ Database setup complete"
}

create_database_user() {
    log_info "Creating database and user..."
    
    # Create database
    sudo -u postgres psql -c "CREATE DATABASE calypso;" 2>/dev/null || log_info "Database already exists"
    
    # Create user
    sudo -u postgres psql -c "CREATE USER calypso WITH PASSWORD '$CALYPSO_DB_PASSWORD';" 2>/dev/null || {
        log_info "User already exists, updating password..."
        sudo -u postgres psql -c "ALTER USER calypso WITH PASSWORD '$CALYPSO_DB_PASSWORD';"
    }
    
    # Grant privileges
    sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE calypso TO calypso;"
    sudo -u postgres psql -c "ALTER DATABASE calypso OWNER TO calypso;"
    
    log_info "✓ Database and user created"
}

run_migrations() {
    log_info "Running database migrations..."
    
    # Migrations will be run on first API startup
    # But we can verify the database is accessible
    export PGPASSWORD="$CALYPSO_DB_PASSWORD"
    if psql -h localhost -U calypso -d calypso -c "SELECT 1;" &>/dev/null; then
        log_info "✓ Database connection verified"
    else
        log_warn "Database connection test failed. Migrations will run on first API start."
    fi
    unset PGPASSWORD
}

create_default_admin() {
    log_info "Creating default admin user..."
    
    # Generate admin password
    ADMIN_PASSWORD=$(generate_random_string 16)
    echo "$ADMIN_PASSWORD" > /tmp/calypso_admin_password
    chmod 600 /tmp/calypso_admin_password
    
    # Hash password (using Go's password hashing)
    # This will be done by the API on first login or via setup script
    log_info "Default admin credentials:"
    log_info "  Username: admin"
    log_info "  Password: $ADMIN_PASSWORD"
    log_warn "Please change the default password after first login!"
    
    # Store password hash in database (if API is available)
    # Otherwise, it will be created on first API run
}

