#!/bin/bash
# Complete setup and troubleshooting script

cd /var/www/SkyArtShop/backend

echo "================================================"
echo "SkyArtShop Backend Setup & Troubleshooting"
echo "================================================"
echo ""

# 1. Generate password hash
echo "Step 1: Generating password hash..."
node -e "const bcrypt = require('bcrypt'); bcrypt.hash('Admin123!', 10).then(hash => console.log(hash));" > /tmp/pwhash.txt
HASH=$(cat /tmp/pwhash.txt)
echo "Generated hash: $HASH"
echo ""

# 2. Setup database
echo "Step 2: Setting up database..."
PGPASSWORD=SkyArt2025Pass! psql -U skyartapp -d skyartshop <<EOF
-- Create tables
CREATE TABLE IF NOT EXISTS adminusers (
  id SERIAL PRIMARY KEY,
  email VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255) NOT NULL,
  passwordhash TEXT NOT NULL,
  role VARCHAR(50) DEFAULT 'admin',
  createdat TIMESTAMP DEFAULT NOW(),
  lastlogin TIMESTAMP
);

CREATE TABLE IF NOT EXISTS session (
  sid VARCHAR NOT NULL COLLATE "default",
  sess JSON NOT NULL,
  expire TIMESTAMP(6) NOT NULL,
  PRIMARY KEY (sid)
);

CREATE INDEX IF NOT EXISTS IDX_session_expire ON session (expire);

-- Delete existing admin if present
DELETE FROM adminusers WHERE email = 'admin@skyartshop.com';

-- Insert new admin with generated hash
INSERT INTO adminusers (email, name, passwordhash, role, createdat) 
VALUES ('admin@skyartshop.com', 'Admin User', '$HASH', 'superadmin', NOW());

-- Show result
SELECT id, email, name, role FROM adminusers;
EOF

echo ""
echo "Step 3: Checking if backend is running..."
if pgrep -f "node.*server.js" > /dev/null; then
    echo "✓ Backend is running"
    echo "  PID: $(pgrep -f 'node.*server.js')"
else
    echo "✗ Backend is NOT running"
    echo ""
    echo "Starting backend server..."
    cd /var/www/SkyArtShop/backend
    nohup node server.js > /tmp/skyartshop-backend.log 2>&1 &
    sleep 2
    
    if pgrep -f "node.*server.js" > /dev/null; then
        echo "✓ Backend started successfully"
    else
        echo "✗ Failed to start backend. Check logs:"
        cat /tmp/skyartshop-backend.log
    fi
fi

echo ""
echo "Step 4: Checking port 3001..."
if netstat -tln 2>/dev/null | grep -q ":3001 " || ss -tln 2>/dev/null | grep -q ":3001 "; then
    echo "✓ Port 3001 is listening"
else
    echo "✗ Port 3001 is NOT listening"
fi

echo ""
echo "================================================"
echo "LOGIN CREDENTIALS"
echo "================================================"
echo "URL: http://localhost:3001/admin/login"
echo "     or http://your-domain.com/admin/login"
echo ""
echo "Email:    admin@skyartshop.com"
echo "Password: Admin123!"
echo "================================================"
echo ""
echo "If still having issues, check logs:"
echo "  tail -f /tmp/skyartshop-backend.log"
echo "================================================"
