<?php
declare(strict_types=1);

require_once __DIR__ . '/wp_common.php';

function openai_data_path(array $cfg, string $ref): string {
  $paths = tenant_paths($cfg, $ref);
  $dir = rtrim($paths['tenantDir'], '/') . '/data';
  if (!is_dir($dir) && !@mkdir($dir, 0750, true) && !is_dir($dir)) {
    throw new RuntimeException('Failed to create tenant data directory');
  }
  @chmod($dir, 0750);
  return $dir . '/openai.json';
}

function openai_save_key(array $cfg, string $ref, string $apiKey): bool {
  $path = openai_data_path($cfg, $ref);
  $masterKey = load_wp_master_key($cfg);
  if ($masterKey === '') {
    throw new RuntimeException('Master key missing for OpenAI encryption');
  }
  $blob = crypto_encrypt_aes256gcm($apiKey, $masterKey, 'openai-key');
  $payload = [
    'version' => 1,
    'created_at' => date('c'),
    'blob' => $blob,
  ];
  $json = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
  if ($json === false) {
    return false;
  }
  if (file_put_contents($path, $json, LOCK_EX) === false) {
    return false;
  }
  @chmod($path, 0640);
  return true;
}

function openai_load_key(array $cfg, string $ref): ?string {
  $path = openai_data_path($cfg, $ref);
  if (!is_file($path)) return null;
  $raw = file_get_contents($path);
  if ($raw === false) return null;
  $data = json_decode($raw, true);
  if (!is_array($data) || !isset($data['blob'])) return null;
  $blob = $data['blob'];
  if (!is_array($blob)) return null;
  $masterKey = load_wp_master_key($cfg);
  if ($masterKey === '') return null;
  return crypto_decrypt_aes256gcm($blob, $masterKey, 'openai-key');
}

function openai_delete_key(array $cfg, string $ref): bool {
  $path = openai_data_path($cfg, $ref);
  if (!is_file($path)) return true;
  return unlink($path);
}
