#!/usr/bin/env bun
/**
 * Final auth test with both cookies
 */

import { encryptString } from "./crypto-subtle";

// Load .env
const envFile = Bun.file(".env");
if (await envFile.exists()) {
  const envContent = await envFile.text();
  for (const line of envContent.split("\n")) {
    const [key, ...valueParts] = line.split("=");
    if (key && valueParts.length) {
      process.env[key.trim()] = valueParts.join("=").trim();
    }
  }
}

const EXTERNAL_API = "https://videomanager-api.anyclip.com";
const MAIN_API = "https://videomanager.anyclip.com";
const PASS_CRYPTO_SALT = "$2b$04$wwky7rvtr6BFNaCqntwyie";

async function test() {
  const email = process.env.ANYCLIP_USER || process.env.ANYCLIP_EMAIL;
  const password = process.env.ANYCLIP_PASSWORD;

  console.log("=== Full Auth Test with SubtleCrypto ===\n");

  // Step 1: External login
  console.log("1. External API login...");
  const encryptedPassword = await encryptString(password!, PASS_CRYPTO_SALT);

  const externalResponse = await fetch(`${EXTERNAL_API}/public/auth/login`, {
    method: "POST",
    headers: { Accept: "application/json", "Content-Type": "application/json" },
    body: JSON.stringify({ email, password: encryptedPassword }),
  });

  if (!externalResponse.ok) {
    console.error("   ❌ Failed:", await externalResponse.text());
    process.exit(1);
  }

  const loginData = await externalResponse.json();
  const anyclipCookie = `${loginData.cookieName}=${loginData.cookieValue}`;
  console.log("   ✅ Got anyclip_2020 cookie");

  // Step 2: Main login - capture session cookie
  console.log("\n2. Main API login...");
  const mainLoginResponse = await fetch(`${MAIN_API}/api/auth/login`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      token: loginData.token,
      tcname: loginData.cookieName,
      tcvalue: loginData.cookieValue,
    }),
  });

  // Extract session cookie from Set-Cookie header
  const setCookies = mainLoginResponse.headers.getSetCookie?.() || [];
  const sessionCookie = setCookies
    .find(c => c.startsWith("session="))
    ?.split(";")[0];

  if (!sessionCookie) {
    console.error("   ❌ No session cookie returned");
    process.exit(1);
  }
  console.log("   ✅ Got session cookie");

  // Both cookies needed
  const fullCookie = `${anyclipCookie}; ${sessionCookie}`;
  console.log("\n3. Combined cookies:");
  console.log("   anyclip_2020:", anyclipCookie.substring(0, 40) + "...");
  console.log("   session:", sessionCookie.substring(0, 40) + "...");

  // Test WITHOUT auth
  console.log("\n4. Test /studio WITHOUT cookies...");
  const noAuthResponse = await fetch(`${MAIN_API}/studio`, {
    redirect: "manual",
  });
  console.log("   Status:", noAuthResponse.status);
  console.log("   Redirects?", noAuthResponse.status === 307);

  // Test WITH auth
  console.log("\n5. Test /studio WITH cookies...");
  const authResponse = await fetch(`${MAIN_API}/studio`, {
    redirect: "manual",
    headers: { Cookie: fullCookie },
  });
  console.log("   Status:", authResponse.status);
  console.log("   Got 200?", authResponse.status === 200);

  // Summary
  console.log("\n========================================");
  if (noAuthResponse.status === 307 && authResponse.status === 200) {
    console.log("✅ SubtleCrypto auth VERIFIED");
    console.log("   - Without cookies: redirected (307)");
    console.log("   - With cookies: authenticated (200)");
  } else {
    console.log("❌ Auth verification failed");
    console.log("   - Without: " + noAuthResponse.status);
    console.log("   - With: " + authResponse.status);
  }
}

test().catch(console.error);
