#!/bin/bash
# Register a new scanner device for testing
# Usage: ./scripts/register-scanner-device.sh <device_uuid> [scanner_name] [pin_code]

set -e

DEVICE_UUID="${1}"
SCANNER_NAME="${2:-Development Scanner}"
PIN_CODE="${3:-123456}"

if [ -z "$DEVICE_UUID" ]; then
    echo "ERROR: Device UUID is required!"
    echo ""
    echo "Usage: $0 <device_uuid> [scanner_name] [pin_code]"
    echo ""
    echo "Examples:"
    echo "  $0 'abc123-def456-ghi789' 'Charlie Laptop' '123456'"
    echo "  $0 'F47AC10B-58CC-4372-A567-0E02B2C3D479'"
    echo ""
    echo "To get your device UUID:"
    echo "  1. Open http://localhost:3004/test-uuid in browser"
    echo "  2. Copy the UUID shown"
    echo "  3. Run this script with that UUID"
    exit 1
fi

echo "========================================"
echo "Registering Scanner Device"
echo "========================================"
echo "Device UUID: $DEVICE_UUID"
echo "Scanner Name: $SCANNER_NAME"
echo "PIN Code: $PIN_CODE"
echo "========================================"
echo ""

# Generate bcrypt hash for PIN
PIN_HASH=$(php artisan tinker --execute="echo Hash::make('$PIN_CODE');")

# Insert into database
php artisan tinker --execute="
\DB::table('scanner_devices')->insert([
    'device_uuid' => '$DEVICE_UUID',
    'scanner_name' => '$SCANNER_NAME',
    'pin_code_hash' => '$PIN_HASH',
    'is_active' => true,
    'notes' => 'Development test device - registered via script',
    'created_at' => now(),
    'updated_at' => now()
]);
echo '✅ Scanner device registered successfully!';
"

echo ""
echo "========================================"
echo "✅ REGISTRATION COMPLETE!"
echo "========================================"
echo ""
echo "You can now login at:"
echo "  http://localhost:3004"
echo ""
echo "Enter PIN: $PIN_CODE"
echo "========================================"
