import { expect } from "e2e";
import http from "node:http";
import https from "node:https";
import { readFileSync } from "node:fs";
import { networkInterfaces } from "node:os";
import { test, WEB } from "./t3.ts";

// Real TLS termination and real Chromium cookie storage; no mocked auth responses.
test("HTTPS sessions stay off plaintext and both schemes retain independent sessions", WEB, async ({t3, app, browser}) => {
  await t3.project("Cookie proof");
  await t3.open();
  const credentials = await browser.evaluate(async () => {
    const result: string[] = [];
    for (let i=0; i<3; i++) {
      const response = await fetch('/api/auth/pairing-token', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({scopes:['orchestration:read']})});
      if (!response.ok) throw new Error(`pairing credential: ${response.status}`);
      result.push((await response.json()).credential);
    }
    return result;
  });
  await browser.clearCookies();
  const host = Object.values(networkInterfaces()).flat().find(a=>a?.family==='IPv4' && !a.internal)!.address;
  const upstream = new URL(app.baseUrl);
  const exchanges: {scheme:string; path:string; sent:string[]; set:string[]}[] = [];
  const handler = (scheme:string) => (req:http.IncomingMessage,res:http.ServerResponse) => {
    const row = {scheme,path:req.url!,sent:(req.headers.cookie ?? '').split(';').map(c=>c.trim().split('=')[0]).filter(Boolean),set:[] as string[]};
    exchanges.push(row);
    const request = http.request({hostname:upstream.hostname,port:upstream.port,path:req.url,method:req.method,headers:{...req.headers,host:upstream.host,'x-forwarded-host':req.headers.host,'x-forwarded-proto':scheme}}, response=>{
      row.set = (response.headers['set-cookie'] ?? []).map(c=>c.replace(/=[^;]*/, '=<redacted>'));
      res.writeHead(response.statusCode!,response.headers); response.pipe(res);
    });
    request.on('error',()=>{res.writeHead(502);res.end('upstream unavailable');});
    req.pipe(request);
  };
  const scratch = process.env.COOKIE_PROOF_SCRATCH!;
  const plain = http.createServer(handler('http'));
  const tls = https.createServer({key:readFileSync(`${scratch}/key.pem`),cert:readFileSync(`${scratch}/cert.pem`)},handler('https'));
  const listen = (server:http.Server) => new Promise<number>(resolve=>server.listen(0,'0.0.0.0',()=>resolve((server.address() as {port:number}).port)));
  const httpUrl = `http://${host}:${await listen(plain)}`;
  const httpsUrl = `https://${host}:${await listen(tls)}`;
  const rows: string[] = [];
  const show = async (title:string) => {
    await browser.evaluate(({title,rows})=>{
      document.body.innerHTML='';
      document.body.style.cssText='margin:0;padding:48px;background:#111827;color:#f3f4f6;font:19px/1.65 system-ui';
      const h=document.createElement('h1');h.textContent=title;document.body.append(h);
      const p=document.createElement('p');p.textContent='Real T3 server · Chromium · fresh profile · TLS reverse proxy with X-Forwarded-Proto: https';document.body.append(p);
      const pre=document.createElement('pre');pre.style.cssText='white-space:pre-wrap;font:18px/1.8 monospace';pre.textContent=rows.join('\n');document.body.append(pre);
      const note=document.createElement('p');note.textContent='Observed network responses and browser cookie jar. Credential values redacted.';note.style.color='#9ca3af';document.body.append(note);
    },{title,rows});
  };
  const navigate = async (origin:string) => {
    try { await browser.goto(`${origin}/api/auth/session`); }
    catch (error) {
      if (!String(error).includes('ERR_CERT_AUTHORITY_INVALID')) throw error;
      await browser.keyboard.type('thisisunsafe');
      await browser.goto(`${origin}/api/auth/session`);
    }
  };
  const pair = (credential:string) => browser.evaluate(async credential=>{
    const r=await fetch('/api/auth/browser-session',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({credential})});
    return {status:r.status,body:await r.json()};
  },credential);
  const state = () => browser.evaluate(async ()=> (await (await fetch('/api/auth/session')).json()).authenticated as boolean);
  try {
    await navigate(httpsUrl);
    const first=await pair(credentials[0]!);
    const tlsCookie=(await browser.cookies()).find(c=>c.name.includes('t3_session_'))!;
    rows.push(`1. Pair over HTTPS: POST browser-session → ${first.status}`,`   Set-Cookie: ${exchanges.filter(e=>e.path==='/api/auth/browser-session').at(-1)!.set.join(' | ')}`,`   Browser jar: Secure = ${tlsCookie?.secure}`);
    const httpsAuthenticated=await state();
    await navigate(httpUrl);
    const plaintextAuthenticated=await state();
    const sentOverHttp=exchanges.at(-1)!.sent.includes(tlsCookie.name);
    rows.push(`2. Direct HTTP session: authenticated = ${plaintextAuthenticated}`,`   HTTPS-issued cookie sent over plaintext = ${sentOverHttp}`);
    await show('HTTPS credential on a plaintext request');
    await app.screenshot('https-cookie-plaintext');

    await browser.clearCookies();
    const second=await pair(credentials[1]!);
    const httpCookie=(await browser.cookies()).find(c=>c.name.includes('t3_session_'))!;
    const httpBefore=await state();
    await navigate(httpsUrl);
    const third=await pair(credentials[2]!);
    const cookiesAfter=await browser.cookies();
    const httpPreserved=cookiesAfter.some(c=>c.name===httpCookie.name && c.value===httpCookie.value);
    const httpsCookie=cookiesAfter.find(c=>c.name.includes('t3_session_') && c.name!==httpCookie.name);
    const httpsAfter=await state();
    await navigate(httpUrl);
    const httpAfter=await state();
    const httpCookieStillUsed=exchanges.at(-1)!.sent.includes(httpCookie.name);
    await navigate(httpsUrl);
    const httpsAfterHttp=await state();
    rows.push('',`3. Fresh HTTP pairing → ${second.status}; authenticated = ${httpBefore}`,`4. Re-pair over HTTPS → ${third.status}; authenticated = ${httpsAfter}`,`   Original HTTP cookie preserved unchanged = ${httpPreserved}`,`   Independent HTTPS cookie exists = ${Boolean(httpsCookie)}`,`5. Revisit HTTP: authenticated = ${httpAfter}; original cookie sent = ${httpCookieStillUsed}`,`6. Revisit HTTPS: authenticated = ${httpsAfterHttp}`);
    await show('Session isolation across HTTP and HTTPS');
    await app.screenshot('independent-scheme-sessions');
    await expect({httpsAuthenticated,secure:tlsCookie.secure,sentOverHttp,plaintextAuthenticated,httpBefore,httpPreserved,independentHttpsCookie:Boolean(httpsCookie),httpAfter,httpsAfterHttp}).toEqual({httpsAuthenticated:true,secure:true,sentOverHttp:false,plaintextAuthenticated:false,httpBefore:true,httpPreserved:true,independentHttpsCookie:true,httpAfter:true,httpsAfterHttp:true});
  } finally {
    plain.closeAllConnections();tls.closeAllConnections();
    await Promise.all([new Promise(r=>plain.close(r)),new Promise(r=>tls.close(r))]);
  }
});
