#!/bin/bash

# ================================
# Seraph3 Database Schema Exporter
# ================================
# This script exports the database schema without data for demo/distribution
# Usage: ./database/schema-export.sh

set -e

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

echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}Seraph3 Schema Export${NC}"
echo -e "${GREEN}================================${NC}"
echo ""

# Load database credentials from .env
if [ ! -f .env ]; then
    echo -e "${RED}Error: .env file not found${NC}"
    exit 1
fi

# Extract database credentials
DB_HOST=$(grep DB_HOST= .env | cut -d '=' -f2)
DB_PORT=$(grep DB_PORT= .env | cut -d '=' -f2)
DB_DATABASE=$(grep DB_DATABASE= .env | cut -d '=' -f2)
DB_USERNAME=$(grep DB_USERNAME= .env | cut -d '=' -f2)
DB_PASSWORD=$(grep DB_PASSWORD= .env | cut -d '=' -f2)

# Default port if not set
DB_PORT=${DB_PORT:-3306}

echo -e "${YELLOW}Database:${NC} $DB_DATABASE"
echo -e "${YELLOW}Host:${NC} $DB_HOST:$DB_PORT"
echo ""

# Create output directory
OUTPUT_DIR="database/schema"
mkdir -p "$OUTPUT_DIR"

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
OUTPUT_FILE="$OUTPUT_DIR/seraph_schema_${TIMESTAMP}.sql"

echo -e "${YELLOW}Exporting schema...${NC}"

# Export schema only (no data)
mysqldump \
    --host="$DB_HOST" \
    --port="$DB_PORT" \
    --user="$DB_USERNAME" \
    --password="$DB_PASSWORD" \
    --no-data \
    --skip-comments \
    --skip-add-drop-table \
    --skip-add-locks \
    --skip-disable-keys \
    --skip-set-charset \
    --compact \
    "$DB_DATABASE" > "$OUTPUT_FILE"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Schema exported successfully!${NC}"
    echo -e "${GREEN}  Location: $OUTPUT_FILE${NC}"

    # Create a symlink to latest
    ln -sf "seraph_schema_${TIMESTAMP}.sql" "$OUTPUT_DIR/latest.sql"
    echo -e "${GREEN}  Symlink: $OUTPUT_DIR/latest.sql${NC}"

    # Show file size
    SIZE=$(du -h "$OUTPUT_FILE" | cut -f1)
    echo -e "${YELLOW}  Size: $SIZE${NC}"
    echo ""

    # Show table count
    TABLE_COUNT=$(grep "CREATE TABLE" "$OUTPUT_FILE" | wc -l)
    echo -e "${GREEN}  Tables exported: $TABLE_COUNT${NC}"
    echo ""

    echo -e "${GREEN}================================${NC}"
    echo -e "${GREEN}Next Steps:${NC}"
    echo -e "1. Review the exported schema"
    echo -e "2. Use migrations instead: php artisan migrate"
    echo -e "3. Or import schema: mysql -u user -p database < $OUTPUT_FILE"
    echo -e "${GREEN}================================${NC}"
else
    echo -e "${RED}✗ Schema export failed!${NC}"
    exit 1
fi
