#!/usr/bin/env bash

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

# Get the project root directory (one level up from scripts/)
PROJECT_ROOT=$(dirname "$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")")

# Clear the screen for better visibility
clear

echo -e "${BOLD}${BLUE}===== Supabase TypeScript Type Generator =====${NC}"
echo
echo -e "${YELLOW}⚠️  IMPORTANT: This script must be run on the server hosting the Supabase Docker container.${NC}"
echo -e "It will not work if you're running it from a different machine, even if connected via VPN."
echo
echo -e "Project root: ${BLUE}${PROJECT_ROOT}${NC}"
echo

# Ask for confirmation
read -p "Are you running this script on the Supabase host server? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${RED}Aborted. Please run this script on the server hosting Supabase.${NC}"
    exit 1
fi

# Check for sudo access
if ! sudo -v; then
    echo -e "${RED}Error: This script requires sudo privileges.${NC}"
    exit 1
fi

# Check if .env file exists in project root
ENV_FILE="${PROJECT_ROOT}/.env"
if [ ! -f "$ENV_FILE" ]; then
    echo -e "${RED}Error: .env file not found at ${ENV_FILE}${NC}"
    echo -e "Please create a .env file with the following variables:"
    echo -e "SUPABASE_DB_HOST, SUPABASE_DB_PORT, SUPABASE_DB_USER, SUPABASE_DB_PASSWORD, SUPABASE_DB_NAME"
    exit 1
fi

echo -e "${GREEN}Found .env file at $ENV_FILE${NC}"

# Source the .env file to get environment variables
export $(grep -v '^#' $ENV_FILE | xargs)

# Check if required variables are set
if [ -z "$SUPABASE_DB_HOST" ] || [ -z "$SUPABASE_DB_PORT" ] || [ -z "$SUPABASE_DB_USER" ] || [ -z "$SUPABASE_DB_PASSWORD" ] || [ -z "$SUPABASE_DB_NAME" ]; then
    # Try to use default variables if Supabase-specific ones aren't set
    if [ -z "$SUPABASE_DB_HOST" ]; then SUPABASE_DB_HOST=${DB_HOST:-localhost}; fi
    if [ -z "$SUPABASE_DB_PORT" ]; then SUPABASE_DB_PORT=${DB_PORT:-5432}; fi
    if [ -z "$SUPABASE_DB_USER" ]; then SUPABASE_DB_USER=${DB_USER:-postgres}; fi
    if [ -z "$SUPABASE_DB_PASSWORD" ]; then SUPABASE_DB_PASSWORD=${DB_PASSWORD}; fi
    if [ -z "$SUPABASE_DB_NAME" ]; then SUPABASE_DB_NAME=${DB_NAME:-postgres}; fi

    # Check again after trying defaults
    if [ -z "$SUPABASE_DB_HOST" ] || [ -z "$SUPABASE_DB_PORT" ] || [ -z "$SUPABASE_DB_USER" ] || [ -z "$SUPABASE_DB_PASSWORD" ] || [ -z "$SUPABASE_DB_NAME" ]; then
        echo -e "${RED}Error: Missing required environment variables${NC}"
        echo -e "Please ensure your .env file contains:"
        echo -e "SUPABASE_DB_HOST, SUPABASE_DB_PORT, SUPABASE_DB_USER, SUPABASE_DB_PASSWORD, SUPABASE_DB_NAME"
        echo -e "Or the equivalent DB_* variables"
        exit 1
    fi
fi

# Check if supabase CLI is installed for the sudo user
echo -e "${YELLOW}Checking if Supabase CLI is installed...${NC}"
if ! sudo npx supabase --version &>/dev/null; then
    echo -e "${YELLOW}Supabase CLI not found. Installing...${NC}"
    sudo npm install -g supabase

    if [ $? -ne 0 ]; then
        echo -e "${RED}Failed to install Supabase CLI. Please install it manually:${NC}"
        echo -e "sudo npm install -g supabase"
        exit 1
    fi
    echo -e "${GREEN}Supabase CLI installed successfully.${NC}"
else
    echo -e "${GREEN}Supabase CLI is already installed.${NC}"
fi

echo -e "${YELLOW}Generating Supabase TypeScript types...${NC}"

# Construct the database URL from environment variables
DB_URL="postgres://$SUPABASE_DB_USER:$SUPABASE_DB_PASSWORD@$SUPABASE_DB_HOST:$SUPABASE_DB_PORT/$SUPABASE_DB_NAME"

# Determine the output directory (relative to project root)
OUTPUT_DIR="${PROJECT_ROOT}/src/utils/supabase"
if [ ! -d "$OUTPUT_DIR" ]; then
    echo -e "${YELLOW}Output directory $OUTPUT_DIR not found. Creating...${NC}"
    mkdir -p "$OUTPUT_DIR"
fi

# Create a temporary file for the output
TEMP_FILE=$(mktemp)

# Run the Supabase CLI command with sudo
echo -e "${YELLOW}Running Supabase CLI to generate types...${NC}"
sudo -E npx supabase gen types typescript \
  --db-url "$DB_URL" \
  --schema public > "$TEMP_FILE" 2>&1

# Check if the command was successful
if [ $? -eq 0 ] && [ -s "$TEMP_FILE" ] && ! grep -q "Error" "$TEMP_FILE"; then
    # Move the temp file to the final destination
    mv "$TEMP_FILE" "$OUTPUT_DIR/database.types.ts"
    echo -e "${GREEN}✓ TypeScript types successfully generated at $OUTPUT_DIR/database.types.ts${NC}"

    # Show the first few lines to confirm it looks right
    echo -e "${YELLOW}Preview of generated types:${NC}"
    head -n 10 "$OUTPUT_DIR/types.ts"
    echo -e "${YELLOW}...${NC}"
else
    echo -e "${RED}✗ Failed to generate TypeScript types${NC}"
    echo -e "${RED}Error output:${NC}"
    cat "$TEMP_FILE"
    rm "$TEMP_FILE"
    exit 1
fi

# Clear sensitive environment variables
unset SUPABASE_DB_PASSWORD
unset DB_URL

echo -e "${GREEN}${BOLD}Type generation complete!${NC}"
echo -e "You can now use these types in your Next.js application."
echo -e "Import them with: ${BLUE}import { Database } from '@/utils/supabase/database.types'${NC}"
