<?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'] ?? '';

if ($email === '' || $password === '') json_err('Email and password required');

$db   = db();
$stmt = $db->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$row  = $stmt->fetch();

if (!$row || !password_verify($password, $row['password_hash'])) {
    json_err('Invalid email or password', 401);
}

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

json_ok([
    'token' => $token,
    'user'  => [
        'id'           => $row['id'],
        'email'        => $row['email'],
        'display_name' => $row['display_name'],
        'role'         => $role,
        'bio'          => $row['bio'],
        'photo_url'    => $row['photo_url'],
        'position'     => $row['position'],
        'team_id'      => $row['team_id'],
        'created_at'   => $row['created_at'],
    ],
]);
