#!/bin/bash
# ============================================================================
# ERP GENERIC - CREATE DATABASE SCRIPT
# ============================================================================
# Description: Creates the database and executes all DDL files in order
# Usage: ./scripts/create-database.sh [--skip-seeds]
# ============================================================================

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DATABASE_DIR="$(dirname "$SCRIPT_DIR")"
DDL_DIR="$DATABASE_DIR/ddl"

# Load environment variables
if [ -f "$DATABASE_DIR/.env" ]; then
    source "$DATABASE_DIR/.env"
elif [ -f "$DATABASE_DIR/.env.example" ]; then
    echo -e "${YELLOW}Warning: Using .env.example as .env not found${NC}"
    source "$DATABASE_DIR/.env.example"
fi

# Default values
POSTGRES_HOST="${POSTGRES_HOST:-localhost}"
POSTGRES_PORT="${POSTGRES_PORT:-5432}"
POSTGRES_DB="${POSTGRES_DB:-erp_generic}"
POSTGRES_USER="${POSTGRES_USER:-erp_admin}"
POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-erp_secret_2024}"

# Connection string
export PGPASSWORD="$POSTGRES_PASSWORD"
PSQL_CMD="psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U $POSTGRES_USER"

echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}   ERP GENERIC - DATABASE CREATION${NC}"
echo -e "${BLUE}============================================${NC}"
echo ""
echo -e "Host:     ${GREEN}$POSTGRES_HOST:$POSTGRES_PORT${NC}"
echo -e "Database: ${GREEN}$POSTGRES_DB${NC}"
echo -e "User:     ${GREEN}$POSTGRES_USER${NC}"
echo ""

# Check if PostgreSQL is reachable
echo -e "${BLUE}[1/4] Checking PostgreSQL connection...${NC}"
if ! $PSQL_CMD -d postgres -c "SELECT 1" > /dev/null 2>&1; then
    echo -e "${RED}Error: Cannot connect to PostgreSQL${NC}"
    echo "Make sure PostgreSQL is running and credentials are correct."
    echo "You can start PostgreSQL with: docker-compose up -d"
    exit 1
fi
echo -e "${GREEN}PostgreSQL is reachable!${NC}"

# Drop database if exists
echo -e "${BLUE}[2/4] Dropping existing database if exists...${NC}"
$PSQL_CMD -d postgres -c "DROP DATABASE IF EXISTS $POSTGRES_DB;" 2>/dev/null || true
echo -e "${GREEN}Old database dropped (if existed)${NC}"

# Create database
echo -e "${BLUE}[3/4] Creating database...${NC}"
$PSQL_CMD -d postgres -c "CREATE DATABASE $POSTGRES_DB WITH ENCODING='UTF8' LC_COLLATE='en_US.UTF-8' LC_CTYPE='en_US.UTF-8' TEMPLATE=template0;" 2>/dev/null || \
$PSQL_CMD -d postgres -c "CREATE DATABASE $POSTGRES_DB;"
echo -e "${GREEN}Database '$POSTGRES_DB' created!${NC}"

# Execute DDL files in order
echo -e "${BLUE}[4/4] Executing DDL files...${NC}"
echo ""

DDL_FILES=(
    "00-prerequisites.sql"
    "01-auth.sql"
    "01-auth-extensions.sql"
    "02-core.sql"
    "03-analytics.sql"
    "04-financial.sql"
    "05-inventory.sql"
    "05-inventory-extensions.sql"
    "06-purchase.sql"
    "07-sales.sql"
    "08-projects.sql"
    "09-system.sql"
    "10-billing.sql"
    "11-crm.sql"
    "12-hr.sql"
)

TOTAL=${#DDL_FILES[@]}
CURRENT=0

for ddl_file in "${DDL_FILES[@]}"; do
    CURRENT=$((CURRENT + 1))
    filepath="$DDL_DIR/$ddl_file"

    if [ -f "$filepath" ]; then
        echo -e "  [${CURRENT}/${TOTAL}] Executing ${YELLOW}$ddl_file${NC}..."
        if $PSQL_CMD -d $POSTGRES_DB -f "$filepath" > /dev/null 2>&1; then
            echo -e "  [${CURRENT}/${TOTAL}] ${GREEN}$ddl_file executed successfully${NC}"
        else
            echo -e "  [${CURRENT}/${TOTAL}] ${RED}Error executing $ddl_file${NC}"
            echo "Attempting with verbose output..."
            $PSQL_CMD -d $POSTGRES_DB -f "$filepath"
            exit 1
        fi
    else
        echo -e "  [${CURRENT}/${TOTAL}] ${RED}File not found: $ddl_file${NC}"
        exit 1
    fi
done

echo ""
echo -e "${GREEN}============================================${NC}"
echo -e "${GREEN}   DATABASE CREATED SUCCESSFULLY!${NC}"
echo -e "${GREEN}============================================${NC}"
echo ""
echo -e "Connection string:"
echo -e "${BLUE}postgresql://$POSTGRES_USER:****@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DB${NC}"
echo ""

# Show statistics
echo -e "${BLUE}Database Statistics:${NC}"
$PSQL_CMD -d $POSTGRES_DB -c "
SELECT
    schemaname AS schema,
    COUNT(*) AS tables
FROM pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
GROUP BY schemaname
ORDER BY schemaname;
"

echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo "  1. Load seed data:  ./scripts/load-seeds.sh dev"
echo "  2. Start backend:   cd ../backend && npm run dev"
echo ""
