<?php
require_once __DIR__.'/../../_bootstrap.php';
if($_SERVER['REQUEST_METHOD']!=='POST')jsonResponse(['ok'=>false,'erro'=>'Método não permitido.'],405);
$d=requestJson();$login=sanitize($d['login']??'');$senha=(string)($d['senha']??'');if(!$login||!$senha)jsonResponse(['ok'=>false,'erro'=>'Informe login e senha.'],422);
try{
  afRateLimitOrFail($pdo,'api_login_ip',clientIp(),10,900,900);
  afRateLimitOrFail($pdo,'api_login_account',strtolower($login).'|'.clientIp(),6,900,1200);
  $campo=filter_var($login,FILTER_VALIDATE_EMAIL)?'email':'username';$st=$pdo->prepare("SELECT * FROM af_usuarios WHERE $campo=? LIMIT 1");$st->execute([$login]);$u=$st->fetch();
  if(!$u||!password_verify($senha,$u['senha'])){afRegistrarTentativaLogin($pdo,$login,false,$u?(int)$u['id']:null,'api_credenciais_invalidas');jsonResponse(['ok'=>false,'erro'=>'Credenciais inválidas.'],401);}
  afAssertContaPermitida($pdo,(int)$u['id']);afRegistrarTentativaLogin($pdo,$login,true,(int)$u['id'],'api_login_ok');afResetRateLimit($pdo,'api_login_account',strtolower($login).'|'.clientIp());
  $token=criarSessaoAutenticada($pdo,$u,true);recarregarSessaoUsuario($pdo,(int)$u['id']);$missingLegal=afMissingLegalAcceptances($pdo,(int)$u['id']);jsonResponse(['ok'=>true,'token'=>$token,'usuario'=>usuarioAtual(),'age'=>afResumoIdade($pdo,(int)$u['id']),'requires_legal_acceptance'=>(bool)$missingLegal,'missing_legal_documents'=>array_map(static fn(array $d):array=>['id'=>(int)$d['id'],'key'=>$d['document_key'],'version'=>$d['version_key'],'title'=>$d['title']],$missingLegal)]);
}catch(Throwable $e){jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],429);}
