import { env } from "cloudflare:test";
import app from "../src/app";

export const TEST_LICENSE = "WPB-TEST-1111-2222";

export async function seedLicenseAndBucket(overrides?: {
  storage_bytes_limit?: number;
  retention_days?: number;
}): Promise<void> {
  await env.DB.prepare(
    "INSERT INTO licenses (license_key, plan, storage_bytes_limit, retention_days, max_sites, status) VALUES (?, 'test', ?, ?, 3, 'active')",
  )
    .bind(
      TEST_LICENSE,
      overrides?.storage_bytes_limit ?? 1_000_000,
      overrides?.retention_days ?? 30,
    )
    .run();
  await env.DB.prepare(
    "INSERT INTO buckets (id, name, region, site_count) VALUES (1, 'wpback-test-001', 'eu-central-1', 0)",
  ).run();
}

export async function activateTestSite(
  siteUrl = "https://example.com",
): Promise<{ site_id: string; site_token: string }> {
  const res = await app.request(
    "/v1/sites/activate",
    {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ license_key: TEST_LICENSE, site_url: siteUrl }),
    },
    env,
  );
  if (res.status !== 201) throw new Error(`activate failed: ${res.status}`);
  return (await res.json()) as { site_id: string; site_token: string };
}

export function authHeaders(token: string): Record<string, string> {
  return { "content-type": "application/json", authorization: `Bearer ${token}` };
}
