<?php

declare(strict_types=1);

require_once __DIR__.'/vendor/autoload.php';

use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory;

// Hash the password
$factory = new PasswordHasherFactory([
    'common'      => ['algorithm' => 'bcrypt'],
    'memory-hard' => ['algorithm' => 'argon2i'],
]);

$passwordHasher = $factory->getPasswordHasher('common');
$hashedPassword = $passwordHasher->hash('admin123');

// Connect to database
$pdo = new PDO(
    'pgsql:host=db;port=5432;dbname=inventory',
    'root',
    'root'
);

// Check if table exists
$tableExists = $pdo->query("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'profiles')")->fetchColumn();

if ($tableExists) {
    echo "Table 'profiles' exists.\n";

    // Check if user exists
    $userExists = $pdo->prepare('SELECT COUNT(*) FROM profiles WHERE email = ?');
    $userExists->execute(['admin@admin.com']);

    if ($userExists->fetchColumn() > 0) {
        echo "User admin@admin.com already exists. Updating password...\n";
        $stmt = $pdo->prepare('UPDATE profiles SET password = ? WHERE email = ?');
        $stmt->execute([$hashedPassword, 'admin@admin.com']);
        echo "Password updated!\n";
    } else {
        echo "Creating user admin@admin.com...\n";
        $stmt = $pdo->prepare('INSERT INTO profiles (id, email, first_name, last_name, is_active, roles, password, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())');
        $id   = 'cl'.substr(strtolower(base_convert(random_bytes(12), 2, 36)), 0, 24);
        $stmt->execute([
            $id,
            'admin@admin.com',
            'Admin',
            'User',
            true,
            json_encode(['ROLE_USER', 'ROLE_ADMIN']),
            $hashedPassword,
        ]);
        echo "User created!\n";
    }
} else {
    echo "Table 'profiles' does not exist yet. Run migrations first.\n";
}

echo "\nTest credentials:\n";
echo "Email: admin@admin.com\n";
echo "Password: admin123\n";
