import { expect } from "e2e";
import { IOS, test } from "./t3-mobile.ts";
import { MOBILE_T3_HOME } from "../e2e.config.ts";
import { chmod } from "node:fs/promises";

const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

test("Failed attachment visibly explains disabled Send", { ...IOS, timeout: 900_000 }, async ({ t3, app, screen, device }) => {
  const project = await t3.project("Attachment demo");
  await t3.thread({ project, title: "Attachment proof", messages: ["Hello"] });
  await t3.open();
  await device.locator('label="Attachment proof, Done"').tap();
  const press = (x: number, y: number) => device.unstable_raw.client.interactions.press({ ...device.unstable_raw.selection, x, y, settle: true });
  const add = async (column: number) => {
    await screen.getByRole("button", "Add attachment").tap();
    await screen.getByText("Photo Library", { exact: true }).first().tap();
    // iOS's embedded Photos surface exposes no accessibility controls through the pool.
    await pause(3000);
    await press(65 + column * 134, 400);
    await press(365, 134);
    await screen.getByRole("button", "Add attachment").waitFor();
  };
  const capture = async (label: string) => {
    await pause(1000);
    await app.screenshot(label);
  };
  const reason = () => screen.getByRole("text", "Retry or remove the failed attachment").first();
  await add(0);
  await screen.getByRole("button", "Send", { exact: true }).waitFor();
  await capture("successful-upload");
  const directory = `${MOBILE_T3_HOME}/userdata/attachments`;
  await chmod(directory, 0o555);
  try {
    await add(1);
    await screen.getByRole("button", "Retry or remove the failed attachment").waitFor();
    await capture("failed-collapsed-counter");
    await expect.soft(reason()).toBeVisible();
    await screen.getByRole("textbox").first().tap();
    await screen.getByRole("button", "Retry uploading IMG_0005.jpeg").waitFor();
    await capture("failed-expanded");
    await expect.soft(reason()).toBeVisible();
    await screen.getByRole("button", "Remove IMG_0111.jpg").tap();
    await press(200, 180);
    await capture("failed-compact-visible");
    await expect.soft(reason()).toBeVisible();
  } finally {
    await chmod(directory, 0o775);
  }
  await screen.getByRole("button", "Retry uploading IMG_0005.jpeg").tap();
  await screen.getByRole("button", "Send", { exact: true }).waitFor();
  await capture("retried-successfully");
  await expect.soft(reason()).not.toBeVisible();
});
