<?php
/**
 * Admin-only dev fixture import (local / test environments).
 */

require_once __DIR__ . '/../lib/dev_fixture.php';

$tokenRec = require_valid_token_web();
require_role(['admin'], $tokenRec);

if ($method !== 'POST') {
    json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405);
}

$body = read_json_body();
$action = trim((string)($body['action'] ?? 'import'));

try {
    [$pdo, $tmpDb, $lockFp] = qdb_open_write_or_fail();

    if ($action === 'remove') {
        $result = qdb_remove_dev_test_data($pdo, [
            'usernamePrefix'  => $body['usernamePrefix'] ?? 'dev_',
            'clientCodePrefix' => $body['clientCodePrefix'] ?? 'DEV-CL-',
        ]);
        qdb_save($tmpDb, $lockFp);
        json_success($result);
    }

    if ($action === 'wipeExceptAdmins') {
        $result = qdb_wipe_all_data_except_admins($pdo);
        qdb_save($tmpDb, $lockFp);
        json_success($result);
    }

    $fixture = $body['fixture'] ?? null;
    if (!is_array($fixture)) {
        qdb_discard($tmpDb, $lockFp);
        json_error('MISSING_FIELDS', 'fixture object is required for import', 400);
    }

    $result = qdb_import_dev_fixture($pdo, $fixture);
    qdb_save($tmpDb, $lockFp);
    json_success($result);
} catch (Throwable $e) {
    $labels = [
        'remove'           => 'Remove dev data',
        'wipeExceptAdmins' => 'Wipe database',
        'import'           => 'Import dev fixture',
    ];
    $label = $labels[$action ?? 'import'] ?? 'Dev fixture';
    qdb_handler_fail($e, $label, $pdo ?? null, $tmpDb ?? null, $lockFp ?? null);
}
