import * as NodeHttp from "node:http";
import { EnvironmentHttpApi } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import { FetchHttpClient } from "effect/http";
import { T3_HOME } from "../e2e.config.ts";
import { SCENARIO_LINEAR_PORT } from "./start-app.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Forward the runner's local Linear endpoint to the real test team's API.
const graphql = async (query: string, variables: Record<string, unknown> = {}) => {
  const response = await fetch("https://api.linear.app/graphql", {
    method: "POST", headers: { "Content-Type": "application/json", Authorization: process.env.LINEAR_API_KEY! },
    body: JSON.stringify({ query, variables }),
  });
  const result = await response.json();
  if (result.errors) throw new Error(JSON.stringify(result.errors));
  return result.data;
};

test("Workflow issue listings honor created order while default uses updated order", WEB,
async ({ t3, app, screen }) => {
  const ids: string[] = [];
  const proxy = NodeHttp.createServer(async (req, res) => {
    try {
      const chunks = [];
      for await (const chunk of req) chunks.push(chunk);
      const response = await fetch("https://api.linear.app/graphql", {
        method: "POST", headers: { "Content-Type": "application/json", Authorization: process.env.LINEAR_API_KEY! },
        body: Buffer.concat(chunks).toString(),
      });
      res.writeHead(response.status, { "content-type": "application/json" });
      res.end(await response.text());
    } catch { res.writeHead(502); res.end(); }
  });
  await new Promise<void>(resolve => proxy.listen(SCENARIO_LINEAR_PORT, "127.0.0.1", resolve));
  const primary = makeState(T3_HOME);
  try {
    const tag = `sort-proof-42350-${Date.now()}`;
    const states = await graphql(`query($team: String!) { team(id: $team) { states { nodes { id type } } } }`, { team: process.env.LINEAR_TEST_TEAM_ID });
    const stateId = states.team.states.nodes.find((s: {type:string}) => s.type === "unstarted").id;
    const create = async (title: string) => {
      const data = await graphql(`mutation($input: IssueCreateInput!) { issueCreate(input: $input) { issue { id identifier } } }`, {
        input: { teamId: process.env.LINEAR_TEST_TEAM_ID, stateId, title: `${tag} ${title}` },
      });
      ids.push(data.issueCreate.issue.id);
      return data.issueCreate.issue;
    };
    const older = await create("Older issue");
    const newer = await create("Newer issue");
    await graphql(`mutation($id: String!, $input: IssueUpdateInput!) { issueUpdate(id: $id, input: $input) { success } }`, {
      id: older.id, input: { description: "Updated after the newer issue was created." },
    });
    const workspace = await t3.project("Issue ordering proof");
    await runPromise(Effect.gen(function* () {
      const rpc = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* rpc["issueTrackers.connect"]({ tracker: "linear", token: process.env.LINEAR_API_KEY! });
      const issued = yield* primary.cli(["auth", "session", "issue", "--token-only", "--label", "scenario"]);
      const api = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: app.baseUrl });
      const snapshot = yield* api.projects.snapshot({ headers: { authorization: `Bearer ${issued.stdout.trim()}` } });
      const project = snapshot.projects.find(p => p.workspaceRoot === workspace)!;
      yield* rpc["issueTrackers.bindProject"]({ projectId: project.id, binding: { tracker: "linear", scope: process.env.LINEAR_TEST_TEAM_KEY! } });
      const fs = yield* FileSystem.FileSystem;
      const path = yield* Path.Path;
      const definition = `export default T3.workflow("issue-order", {version: 1, payload: Schema.Struct({})}, Effect.fn(function* () {
        const result = yield* T3.step("Read real Linear issues", {returns: Schema.Struct({created: Schema.String, updated: Schema.String})}, Effect.gen(function* () {
          const created = yield* T3.issues.list({project: ${JSON.stringify(workspace)}, state: "open", query: ${JSON.stringify(tag)}, sort: "created"});
          const updated = yield* T3.issues.list({project: ${JSON.stringify(workspace)}, state: "open", query: ${JSON.stringify(tag)}});
          return {created: created.map(i => i.displayKey).join(" → "), updated: updated.map(i => i.displayKey).join(" → ")};
        }));
        yield* T3.title("Created: " + result.created + " | Updated: " + result.updated);
      }));`;
      yield* fs.makeDirectory(path.join(T3_HOME, "workflows"), {recursive: true});
      yield* fs.writeFileString(path.join(T3_HOME, "workflows/issue-order.ts"), definition);
      yield* rpc["server.updateSettings"]({patch: {workflowsEnabled: true}});
    }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer)));
    const started = await runPromise(primary.cli(["workflow", "start", "issue-order", "--key", "one", "--json"]));
    const {run} = JSON.parse(started.stdout);
    await t3.open(`/workflows?run=${run.runId}`);
    const heading = screen.getByRole("heading", "Created:", {exact: false});
    await heading.waitFor({timeout: 60_000});
    await app.screenshot("workflow-issue-order");
    await expect(heading).toHaveText(`Created: ${newer.identifier} → ${older.identifier} | Updated: ${older.identifier} → ${newer.identifier}`);
  } finally {
    for (const id of ids) await graphql(`mutation($id: String!) { issueDelete(id: $id) { success } }`, {id});
    await new Promise(resolve => proxy.close(resolve));
  }
});
