<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/common/auth_middleware.php';
require_once dirname(__DIR__) . '/common/backup_service.php';
require_once dirname(__DIR__) . '/common/portal_auth.php';
require_once dirname(__DIR__) . '/common/demo_request_service.php';
require_once dirname(__DIR__) . '/common/customer_cleanup.php';

function golder_api_auth(string $scope = 'desktop_sync'): array
{
    $master = golder_master_pdo();
    golder_apply_default_rate_limit($master, golder_api_rate_limit_route_key($scope), 120, 60);
    $tokenRow = golder_auth_token($master, $scope);

    $customerId = (int)($tokenRow['customer_id'] ?? 0);
    $customer = golder_customer_by_id($master, $customerId);
    if (!$customer) {
        golder_json_response(['status' => 'error', 'code' => 'CUSTOMER_NOT_FOUND'], 404);
    }

    $customer = golder_enforce_customer_plan($master, $customerId) ?: $customer;

    return [
        'master' => $master,
        'token' => $tokenRow,
        'customer' => $customer,
        'customer_id' => $customerId,
    ];
}

function golder_api_input(): array
{
    $json = golder_read_json_body();
    if ($json) {
        return $json;
    }
    return $_POST;
}


