<?php
// =============================================================================
// POST /auth — the AppInfoModel-returning login.
//
// Request body (JSON):
//   { "data": "<envelope>" }
// Decoded inner JSON:
//   { "app_device_id": base64(android_id),
//     "app_type":      "phone"|"tv"|...,
//     "version":       "4.3",
//     "is_paid":       false }
//
// Headers: 6 hash/token headers (X-Gc-Token, x-hash, x-hash-2, x-token,
//          x-token-2, x-token-3). We log them but don't validate in v1.
//
// Response: the full AppInfoModel JSON (see auth_response_example.json).
// =============================================================================

require_once __DIR__ . '/includes/client_common.php';

require_method('POST');

$inner = client_decoded_body();
if (!is_array($inner)) {
    json_error('invalid envelope', 400);
}

$app_device_id = (string)($inner['app_device_id'] ?? '');
$app_type      = (string)($inner['app_type']      ?? 'phone');
$version       = (string)($inner['version']       ?? '4.3');
$is_paid       = (bool)  ($inner['is_paid']       ?? false);

if ($app_device_id === '') {
    json_error('missing app_device_id', 400);
}

$device = client_get_or_create_device($app_device_id, $app_type, $version, $is_paid ? 1 : 0);
$resp   = build_app_info_model($device);

client_log_request((int)$device['id'], 'POST', '/auth',
                   client_request_headers(), $inner, 200, $resp);

// Wire format: response body is { "data": "<json-string>" } — the inner JSON
// is the AppInfoModel-shaped payload (IBO Ultra wire format). The client side does the
// equivalent of  json.loads(body)['data']  then  json.loads(...)  again.
json_response(['data' => json_encode($resp, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
