<?php
require_once __DIR__ . '/../config/helpers.php';
cors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') json_err('Method not allowed', 405);

$b = body();
$email       = trim($b['email'] ?? '');
$password    = $b['password'] ?? '';
$displayName = trim($b['display_name'] ?? '');

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) json_err('Invalid email');
if (strlen($password) < 6) json_err('Password must be at least 6 characters');

$db = db();

$stmt = $db->prepare('SELECT id FROM users WHERE email = ?');
$stmt->execute([$email]);
if ($stmt->fetch()) json_err('Email already registered', 409);

$id   = uuid();
$hash = password_hash($password, PASSWORD_BCRYPT);
$role = resolve_role($email, 'player');

$db->prepare(
    'INSERT INTO users (id, email, password_hash, display_name, role) VALUES (?, ?, ?, ?, ?)'
)->execute([$id, $email, $hash, $displayName, $role]);

$token = JWT::encode(['uid' => $id, 'email' => $email, 'role' => $role]);

json_ok([
    'token' => $token,
    'user'  => [
        'id'           => $id,
        'email'        => $email,
        'display_name' => $displayName,
        'role'         => $role,
        'bio'          => '',
        'photo_url'    => null,
        'position'     => null,
        'team_id'      => null,
        'created_at'   => date('c'),
    ],
], 201);
