import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { CommandId, ThreadId, MessageId, ChatAttachmentId } from "@t3tools/contracts";
import { MOBILE, MOBILE_T3_HOME } from "../e2e.config.ts";
import { environmentId, rpcClient, runPromise } from "./t3.ts";
import { IOS, test } from "./t3-mobile.ts";

test("CSV headings remain below the iPad navigation bar", IOS, async ({ t3, app, screen, device }) => {
  const csv = "Region,Quarter,Product,Revenue,Units,Owner,Channel,Notes\n" + Array.from({length:60}, (_,i) => `J${i+1},Q1,Product ${i+1},${1000+i},${20+i},Owner ${i+1},Direct,Synthetic sales note ${i+1}`).join("\n");
  const project = await t3.project("Sales preview", { "sales.csv": csv });
  const { threadId } = await t3.thread({ project, title: "Sales CSV", messages: ["first"] });
  const origin = `http://${MOBILE.host}:${MOBILE.serverPort}`;
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const rpc = yield* rpcClient(MOBILE_T3_HOME, origin);
    const upload = yield* rpc["attachments.createUploadUrl"]({type:"file", name:"sales.csv", mimeType:"text/csv", sizeBytes:Buffer.byteLength(csv)});
    yield* Effect.promise(async () => {
      const response = await fetch(`${origin}${upload.relativeUrl}`, {method:"POST", body:csv, headers:{"Content-Type":"text/csv"}});
      if (!response.ok) throw new Error(`CSV upload: ${response.status} ${await response.text()}`);
    });
    yield* rpc["orchestration.dispatchCommand"]({
      type:"message.dispatch", commandId:CommandId.make(crypto.randomUUID()), threadId:ThreadId.make(threadId), messageId:MessageId.make(crypto.randomUUID()),
      createdBy:"user", creationSource:"mobile", text:"Inspect this sales CSV", attachments:[{type:"file",id:ChatAttachmentId.make(upload.attachmentId),name:"sales.csv",mimeType:"text/csv",sizeBytes:Buffer.byteLength(csv)}], dispatchMode:{type:"start_immediately"}
    });
  })));
  await device.setAppearance("light");
  await device.setOrientation("landscape-left");
  await t3.open();
  await screen.getByText("Sales CSV", {exact:false}).first().waitFor({timeout:120_000});
  const environment = await runPromise(environmentId(origin));
  await device.openLink(`t3code-dev://threads/${environment}/${threadId}`, {app:"com.t3tools.t3code.dev"});
  await device.alert("accept").catch(() => {});
  const attachment = screen.getByRole("button", "Open sales.csv", {exact:false});
  await attachment.tap({timeout:60_000});
  const heading = screen.getByText("Region", {exact:true});
  await heading.waitFor();
  await app.screenshot("csv-first-open");
  const initial = await heading.boundingBox();
  await screen.swipe({from:{x:500,y:600},to:{x:500,y:200},duration:1500});
  await app.screenshot("csv-scrolled-down");
  await screen.swipe({from:{x:500,y:200},to:{x:500,y:650},duration:1500});
  await screen.swipe({from:{x:500,y:200},to:{x:500,y:650},duration:1500});
  await app.screenshot("csv-returned-top");
  const returned = await heading.boundingBox();
  await screen.tapAt({x:412, y:54});
  await attachment.tap();
  await heading.waitFor();
  await app.screenshot("csv-reopened");
  const reopened = await heading.boundingBox();
  await screen.swipe({from:{x:950,y:350},to:{x:350,y:350},duration:1500});
  await app.screenshot("csv-horizontal-scroll");
  expect(initial?.y).toBeGreaterThan(80);
  expect(returned?.y).toBeGreaterThan(80);
  expect(reopened?.y).toBeGreaterThan(80);
  await expect(screen.getByText("Notes", {exact:true})).toBeVisible();
});
