#!/bin/bash
#
# AtlasOS - Calypso Test User Setup Script
# Creates a test admin user in the database
#

set -euo pipefail

DB_NAME="${DB_NAME:-calypso}"
DB_USER="${DB_USER:-calypso}"
ADMIN_USER="${ADMIN_USER:-admin}"
ADMIN_EMAIL="${ADMIN_EMAIL:-admin@calypso.local}"
ADMIN_PASS="${ADMIN_PASS:-admin123}"

echo "Setting up test admin user..."

sudo -u postgres psql "$DB_NAME" << EOF
-- Create admin user (password is plaintext for testing - replace with hash in production)
INSERT INTO users (id, username, email, password_hash, full_name, is_active, is_system)
VALUES (
  gen_random_uuid(),
  '$ADMIN_USER',
  '$ADMIN_EMAIL',
  '$ADMIN_PASS',  -- TODO: Replace with proper Argon2id hash in production
  'Administrator',
  true,
  false
) ON CONFLICT (username) DO UPDATE SET
  email = EXCLUDED.email,
  password_hash = EXCLUDED.password_hash,
  full_name = EXCLUDED.full_name,
  is_active = true;

-- Assign admin role
INSERT INTO user_roles (user_id, role_id)
SELECT u.id, r.id
FROM users u, roles r
WHERE u.username = '$ADMIN_USER' AND r.name = 'admin'
ON CONFLICT DO NOTHING;

-- Verify user was created
SELECT u.username, u.email, r.name as role
FROM users u
LEFT JOIN user_roles ur ON u.id = ur.user_id
LEFT JOIN roles r ON ur.role_id = r.id
WHERE u.username = '$ADMIN_USER';
EOF

echo ""
echo "✓ Test admin user created:"
echo "  Username: $ADMIN_USER"
echo "  Password: $ADMIN_PASS"
echo "  Email: $ADMIN_EMAIL"
echo ""
echo "You can now login with:"
echo "  curl -X POST http://localhost:8080/api/v1/auth/login \\"
echo "    -H 'Content-Type: application/json' \\"
echo "    -d '{\"username\":\"$ADMIN_USER\",\"password\":\"$ADMIN_PASS\"}'"

