#!/bin/bash

set -e

MODULE_IMPORT="quantex.com.ar/multidb"
MODULE_NAME="multidb"
DB_VAR_NAME="database"

echo "Removing all references to '$MODULE_NAME' and replacing with 'database/sql' where needed..."

FILES=$(find ./src -type f -name "*.go")

for file in $FILES; do
  echo "Processing $file"

  # 1. Remove explicit import by module path
  perl -pi -e "s|.*$MODULE_IMPORT.*\n||g" "$file"

  # 2. Remove any import line containing 'multidb'
  perl -pi -e 's|.*"[^"]*multidb[^"]*".*\n||g' "$file"

  # 3. Replace multidb.New(...) with sql.Open(...)
  perl -pi -e "s|$MODULE_NAME\.New\s*\(\s*serviceName:\s*\"[^\"]*\",\s*(.*?)\)|sql.Open(\"postgres\", \1)|g" "$file"

  # 4. Comment out database.Start()
  perl -pi -e "s|$DB_VAR_NAME\.Start\(\)|// $DB_VAR_NAME.Start() removed, not needed in database/sql|g" "$file"

  # 5. Remove any line containing .PeriodicDBPing
  perl -pi -e "s|.*\.PeriodicDBPing.*\n||g" "$file"

  # 6. Remove any reference to *multidb.Type
  perl -pi -e "s|\*?$MODULE_NAME\.[A-Za-z0-9_]+||g" "$file"

  # 7. Remove the field 'MultiDB multidb.Config' from structs
  perl -pi -e "s|MultiDB\s+$MODULE_NAME\.Config\s*||g" "$file"

  # 8. Remove orphan field 'MultiDB' with no type
  perl -pi -e 's/^\s*MultiDB\s*\n//g' "$file"

  # 9. Remove field 'db' with no type (after type removal)
  perl -pi -e "s|^\s*db\s*\n||g" "$file"

  # 10. Replace store.Config{MultiDB: ...} with store.Config{}
  perl -pi -e 's|store\.Config\s*{\s*MultiDB:\s*[^}]+}|store.Config{}|g' "$file"

  # 11. Remove p.db.Close() line
  perl -pi -e 's|^[ \t]*p\.db\.Close\(\)[ \t]*;?[ \t]*\n||g' "$file"

  # 12. Remove block from database initialization to return s, nil
  perl -0777 -pi -e 's|database\s*,\s*err\s*:=.*?\n.*?return s,\s*nil\n||gs' "$file"

  # 13. If function New(...) is now empty, insert 'return nil, nil'
  perl -0777 -pi -e 's|func\s+New\([^\)]*\)\s*\(\*Store,\s*error\)\s*{\s*}|func New(config Config) (*Store, error) {\n    return nil, nil\n}|g' "$file"

  # 14. Clean Store struct, leave it empty if db field was removed
  perl -0777 -pi -e 's|type Store struct\s*{\s*db\s*:.*?\n\s*}|type Store struct {}|g' "$file"
done

# 15. Remove import "database/sql" if not used anymore
for file in $FILES; do
  if ! grep -q "sql." "$file" && grep -q '"database/sql"' "$file"; then
    echo "Removing unused import 'database/sql' in $file"
    perl -pi -e 's|.*"database/sql".*\n||g' "$file"
  fi
done

# 16. Remove the module requirement from go.mod and clean go.sum
echo "Cleaning go.mod and go.sum..."
go mod edit -droprequire=$MODULE_IMPORT || true
go mod tidy
go mod vendor || true

# 17. Remove vendored copy if exists
rm -rf ./vendor/quantex.com.ar/multidb || true

echo "multidb module fully removed."