#!/bin/bash

# Configuration
# Derive monorepo root
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ROOT_DIR="$( dirname "$SCRIPT_DIR" )"
DB_PATH="$ROOT_DIR/packages/cms-infra/database/data.db"

if [ ! -f "$DB_PATH" ]; then
    echo "❌ Database not found at $DB_PATH"
    exit 1
fi

reconcile_table() {
    local TABLE=$1
    echo "🔍 Reconciling table: $TABLE"

    # 1. Get all columns from SQLite
    COLUMNS=$(sqlite3 "$DB_PATH" "PRAGMA table_info($TABLE);" | cut -d'|' -f2)

    for COL in $COLUMNS; do
        # Skip system columns if needed, but usually it's safer to just check if they exist in Directus
        
        # 2. Check if field exists in directus_fields
        EXISTS=$(sqlite3 "$DB_PATH" "SELECT count(*) FROM directus_fields WHERE collection = '$TABLE' AND field = '$COL';")
        
        if [ "$EXISTS" -eq 0 ]; then
            echo "➕ Registering missing field: $TABLE.$COL"
            
            # Determine a basic interface based on column name or type (very simplified)
            INTERFACE="input"
            case $COL in
                *id) INTERFACE="numeric" ;;
                *text) INTERFACE="input-multiline" ;;
                company|person|user_created|user_updated|feedback_id) INTERFACE="select-dropdown-m2o" ;;
                date_created|date_updated) INTERFACE="datetime" ;;
                screenshot|logo) INTERFACE="file" ;;
                status|type) INTERFACE="select-dropdown" ;;
            esac

            sqlite3 "$DB_PATH" "INSERT INTO directus_fields (collection, field, interface) VALUES ('$TABLE', '$COL', '$INTERFACE');"
        else
            echo "✅ Field already registered: $TABLE.$COL"
        fi
    done
}

# Run for known problematic tables
reconcile_table "visual_feedback"
reconcile_table "visual_feedback_comments"
reconcile_table "people"
reconcile_table "leads"
reconcile_table "client_users"
reconcile_table "companies"

echo "✨ SQL Reconciliation complete!"
