#!/bin/bash
# ============================================================================
# Export Database Schema (NO DATA)
# ============================================================================
# Esporta solo la struttura del database (DDL) senza dati sensibili
# Da committare su git per versioning dello schema

set -e

# Colori
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${BLUE}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   Database Schema Export                     ║${NC}"
echo -e "${BLUE}╚═══════════════════════════════════════════════╝${NC}"
echo ""

# Carica configurazione da .env
if [ -f "/opt/ids/.env" ]; then
    source /opt/ids/.env
    echo -e "${GREEN}✅ Configurazione caricata da .env${NC}"
else
    echo -e "${RED}❌ File .env non trovato${NC}"
    exit 1
fi

# File output
SCHEMA_FILE="/opt/ids/database-schema/schema.sql"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Crea directory se non esiste
mkdir -p /opt/ids/database-schema

echo -e "${BLUE}📄 Export schema da database: ${PGDATABASE}${NC}"

# Export solo schema (--schema-only = NO DATA)
export PGPASSWORD="$PGPASSWORD"
pg_dump \
    -h "${PGHOST:-127.0.0.1}" \
    -p "${PGPORT:-5432}" \
    -U "${PGUSER}" \
    -d "${PGDATABASE}" \
    --schema-only \
    --no-owner \
    --no-privileges \
    > "$SCHEMA_FILE"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ Schema esportato: $SCHEMA_FILE${NC}"
    
    # Statistiche
    TABLES=$(grep -c "CREATE TABLE" "$SCHEMA_FILE" || echo 0)
    INDEXES=$(grep -c "CREATE INDEX" "$SCHEMA_FILE" || echo 0)
    SIZE=$(du -h "$SCHEMA_FILE" | cut -f1)
    
    echo ""
    echo -e "${BLUE}📊 Statistiche:${NC}"
    echo -e "   - Tabelle: ${GREEN}${TABLES}${NC}"
    echo -e "   - Indici: ${GREEN}${INDEXES}${NC}"
    echo -e "   - Dimensione: ${GREEN}${SIZE}${NC}"
    echo ""
    echo -e "${GREEN}✅ File pronto per commit su git${NC}"
else
    echo -e "${RED}❌ Errore durante export schema${NC}"
    exit 1
fi
