import { test, expect } from "./fixtures/test";

/**
 * Integration tests that require the full dev stack:
 * - PostgreSQL (for sessions)
 * - BRouter (for route computation)
 *
 * In CI, these services are started by the workflow.
 * Locally, run `pnpm dev:full` first (with E2E=true for the callback tests).
 */

const JOURNAL = "http://localhost:3000";
const PLANNER = "http://localhost:3001";

const VALID_GPX = `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1">
  <trk><trkseg>
    <trkpt lat="52.52" lon="13.405"><ele>34</ele></trkpt>
    <trkpt lat="52.51" lon="13.38"><ele>40</ele></trkpt>
    <trkpt lat="52.50" lon="13.35"><ele>35</ele></trkpt>
  </trkseg></trk>
</gpx>`;

const ONE_POINT_GPX = `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1">
  <trk><trkseg>
    <trkpt lat="52.52" lon="13.405"><ele>34</ele></trkpt>
  </trkseg></trk>
</gpx>`;

test.describe("Integration: Planner callback → geometry stored", () => {
  test("valid GPX stores geometry atomically", async ({ request }) => {
    const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
    expect(seedResp.ok()).toBeTruthy();
    const { routeId, token } = await seedResp.json() as { routeId: string; token: string };

    const callbackResp = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
      headers: { Authorization: `Bearer ${token}` },
      data: { gpx: VALID_GPX },
    });
    expect(callbackResp.status()).toBe(200);

    const geomResp = await request.get(`${JOURNAL}/api/e2e/route/${routeId}`);
    const { hasGeom } = await geomResp.json() as { hasGeom: boolean };
    expect(hasGeom).toBe(true);
  });

  test("invalid GPX returns 400 and does not store geometry", async ({ request }) => {
    const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
    const { routeId, token } = await seedResp.json() as { routeId: string; token: string };

    const callbackResp = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
      headers: { Authorization: `Bearer ${token}` },
      data: { gpx: ONE_POINT_GPX },
    });
    expect(callbackResp.status()).toBe(400);
    const body = await callbackResp.json() as { error: string };
    expect(body.error).toMatch(/at least 2 track points/);

    const geomResp = await request.get(`${JOURNAL}/api/e2e/route/${routeId}`);
    const { hasGeom } = await geomResp.json() as { hasGeom: boolean };
    expect(hasGeom).toBe(false);
  });

  test("missing token returns 401", async ({ request }) => {
    const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
    const { routeId } = await seedResp.json() as { routeId: string };

    const resp = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
      data: { gpx: VALID_GPX },
    });
    expect(resp.status()).toBe(401);
  });

  test("token is single-use — second submit is rejected (Phase B replay guard)", async ({ request }) => {
    const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
    const { routeId, token } = await seedResp.json() as { routeId: string; token: string };

    // First save succeeds.
    const first = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
      headers: { Authorization: `Bearer ${token}` },
      data: { gpx: VALID_GPX },
    });
    expect(first.status()).toBe(200);

    // Second attempt with the *same* token must fail — the jti has
    // been consumed.
    const second = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
      headers: { Authorization: `Bearer ${token}` },
      data: { gpx: VALID_GPX },
    });
    expect(second.status()).toBe(401);
    const body = await second.json() as { error: string };
    expect(body.error).toMatch(/consumed|already/i);
  });
});

test.describe("Integration: Journal ↔ Planner handoff", () => {
  test("GPX import → view route → export GPX", async ({ request }) => {
    const gpx = `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">
  <wpt lat="52.52" lon="13.405"><name>Berlin</name></wpt>
  <wpt lat="52.50" lon="13.35"><name>Tiergarten</name></wpt>
  <trk><trkseg>
    <trkpt lat="52.52" lon="13.405"><ele>34</ele></trkpt>
    <trkpt lat="52.51" lon="13.38"><ele>40</ele></trkpt>
    <trkpt lat="52.50" lon="13.35"><ele>35</ele></trkpt>
  </trkseg></trk>
</gpx>`;

    const sessionResp = await request.post(`${PLANNER}/api/sessions`, {
      data: { gpx },
    });
    expect(sessionResp.ok()).toBeTruthy();
    const session = await sessionResp.json();
    expect(session.initialWaypoints).toHaveLength(2);
    expect(session.initialWaypoints[0].name).toBe("Berlin");
  });

  test("GPX import with overnight waypoints preserves isDayBreak", async ({ request }) => {
    const gpx = `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">
  <wpt lat="52.52" lon="13.405"><name>Berlin</name></wpt>
  <wpt lat="51.84" lon="12.243"><name>Dessau</name><type>overnight</type></wpt>
  <wpt lat="50.98" lon="11.028"><name>Erfurt</name></wpt>
  <trk><trkseg>
    <trkpt lat="52.52" lon="13.405"><ele>34</ele></trkpt>
    <trkpt lat="51.84" lon="12.243"><ele>80</ele></trkpt>
    <trkpt lat="50.98" lon="11.028"><ele>195</ele></trkpt>
  </trkseg></trk>
</gpx>`;

    const sessionResp = await request.post(`${PLANNER}/api/sessions`, {
      data: { gpx },
    });
    expect(sessionResp.ok()).toBeTruthy();
    const session = await sessionResp.json();
    expect(session.initialWaypoints).toHaveLength(3);
    expect(session.initialWaypoints[1].name).toBe("Dessau");
    // isDayBreak should be preserved through GPX parsing
    expect(session.initialWaypoints[1].isDayBreak).toBe(true);
  });
});

test.describe("Integration: POI metadata roundtrip", () => {
  test("GPX with POI extensions round-trips through Journal and renders on detail page", async ({ page, request }) => {
    const gpx = `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1" xmlns:trails="https://trails.cool/gpx/1">
  <wpt lat="52.52" lon="13.405">
    <name>Bike Shop Berlin</name>
    <extensions>
      <trails:poi osmId="123456">
        <trails:tag k="phone" v="+49 30 12345"/>
        <trails:tag k="website" v="https://bikeshop.example"/>
        <trails:tag k="opening_hours" v="Mo-Fr 09:00-18:00"/>
      </trails:poi>
    </extensions>
  </wpt>
  <trk><trkseg>
    <trkpt lat="52.52" lon="13.405"><ele>34</ele></trkpt>
    <trkpt lat="52.51" lon="13.38"><ele>40</ele></trkpt>
    <trkpt lat="52.50" lon="13.35"><ele>35</ele></trkpt>
  </trkseg></trk>
</gpx>`;

    const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
    expect(seedResp.ok()).toBeTruthy();
    const { routeId, token } = await seedResp.json() as { routeId: string; token: string };

    const callbackResp = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
      headers: { Authorization: `Bearer ${token}` },
      data: { gpx },
    });
    expect(callbackResp.status()).toBe(200);

    // Navigate to route detail page and check POI details are rendered
    await page.goto(`${JOURNAL}/routes/${routeId}`);
    await expect(page.getByText("Bike Shop Berlin")).toBeVisible();
    await expect(page.getByText("+49 30 12345")).toBeVisible();
    await expect(page.getByText("Mo-Fr 09:00-18:00")).toBeVisible();
    await expect(page.getByRole("link", { name: "https://bikeshop.example" })).toBeVisible();
  });

  test("GPX without POI extensions shows no waypoints section", async ({ page, request }) => {
    const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
    const { routeId, token } = await seedResp.json() as { routeId: string; token: string };
    await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
      headers: { Authorization: `Bearer ${token}` },
      data: { gpx: VALID_GPX },
    });
    await page.goto(`${JOURNAL}/routes/${routeId}`);
    await expect(page.getByText("Waypoints")).not.toBeVisible();
  });
});

test.describe("Integration: BRouter routing", () => {
  // Helper: mint a planner session so our /api/route calls satisfy
  // the session-bound gate introduced alongside this test file.
  async function createSessionId(
    request: import("@playwright/test").APIRequestContext,
  ): Promise<string> {
    const resp = await request.post(`${PLANNER}/api/sessions`, { data: {} });
    const payload = (await resp.json()) as { sessionId: string };
    return payload.sessionId;
  }

  test("computes route between Berlin waypoints", async ({ request }) => {
    const sessionId = await createSessionId(request);
    const response = await request.post(`${PLANNER}/api/route`, {
      data: {
        waypoints: [
          { lat: 52.516, lon: 13.377 },
          { lat: 52.515, lon: 13.351 },
        ],
        profile: "trekking",
        sessionId,
      },
    });
    expect(response.ok()).toBeTruthy();
    const enriched = await response.json();
    expect(enriched.geojson.features).toHaveLength(1);
    expect(enriched.geojson.features[0].geometry.type).toBe("LineString");
    expect(enriched.coordinates.length).toBeGreaterThan(10);
  });

  test("routes through all waypoints (segment by segment)", async ({ request }) => {
    const sessionId = await createSessionId(request);
    const response = await request.post(`${PLANNER}/api/route`, {
      data: {
        waypoints: [
          { lat: 52.520, lon: 13.405 },
          { lat: 52.516, lon: 13.377 },
          { lat: 52.510, lon: 13.390 },
        ],
        profile: "trekking",
        sessionId,
      },
    });
    expect(response.ok()).toBeTruthy();
    const enriched = await response.json();
    const coords = enriched.coordinates;

    const nearMiddle = coords.some(
      (c: number[]) =>
        Math.abs(c[1] - 52.516) < 0.005 && Math.abs(c[0] - 13.377) < 0.005,
    );
    expect(nearMiddle).toBeTruthy();
  });

  test("returns rate limit headers", async ({ request }) => {
    const sessionId = await createSessionId(request);
    const response = await request.post(`${PLANNER}/api/route`, {
      data: {
        waypoints: [
          { lat: 52.516, lon: 13.377 },
          { lat: 52.515, lon: 13.351 },
        ],
        sessionId,
      },
    });
    expect(response.headers()["x-ratelimit-remaining"]).toBeDefined();
  });

  test("rejects with fewer than 2 waypoints", async ({ request }) => {
    const sessionId = await createSessionId(request);
    const response = await request.post(`${PLANNER}/api/route`, {
      data: {
        waypoints: [{ lat: 52.516, lon: 13.377 }],
        sessionId,
      },
    });
    expect(response.status()).toBe(400);
  });

  test("returns enriched route with segment boundaries", async ({ request }) => {
    const sessionId = await createSessionId(request);
    const response = await request.post(`${PLANNER}/api/route`, {
      data: {
        waypoints: [
          { lat: 52.520, lon: 13.405 },
          { lat: 52.516, lon: 13.377 },
          { lat: 52.510, lon: 13.390 },
        ],
        profile: "trekking",
        sessionId,
      },
    });
    expect(response.ok()).toBeTruthy();
    const enriched = await response.json();

    // EnrichedRoute fields
    expect(enriched.coordinates).toBeDefined();
    expect(enriched.coordinates.length).toBeGreaterThan(10);
    expect(enriched.coordinates[0]).toHaveLength(3); // [lon, lat, ele]
    expect(enriched.segmentBoundaries).toBeDefined();
    expect(enriched.segmentBoundaries).toHaveLength(2); // 3 waypoints = 2 segments
    expect(enriched.segmentBoundaries[0]).toBe(0);
    expect(enriched.totalLength).toBeGreaterThan(0);
    expect(enriched.geojson).toBeDefined();
    expect(enriched.geojson.features[0].geometry.type).toBe("LineString");
  });

  test("accepts no-go areas parameter", async ({ request }) => {
    const sessionId = await createSessionId(request);
    const response = await request.post(`${PLANNER}/api/route`, {
      data: {
        waypoints: [
          { lat: 52.516, lon: 13.377 },
          { lat: 52.515, lon: 13.351 },
        ],
        profile: "trekking",
        sessionId,
        noGoAreas: [
          {
            points: [
              { lat: 52.516, lon: 13.365 },
              { lat: 52.514, lon: 13.365 },
              { lat: 52.514, lon: 13.370 },
              { lat: 52.516, lon: 13.370 },
            ],
          },
        ],
      },
    });
    expect(response.ok()).toBeTruthy();
    const enriched = await response.json();
    expect(enriched.geojson.features).toHaveLength(1);
    expect(enriched.geojson.features[0].geometry.type).toBe("LineString");
  });

  test("rejects /api/route without a sessionId (session-bound)", async ({ request }) => {
    const response = await request.post(`${PLANNER}/api/route`, {
      data: {
        waypoints: [
          { lat: 52.516, lon: 13.377 },
          { lat: 52.515, lon: 13.351 },
        ],
        profile: "trekking",
      },
    });
    expect(response.status()).toBe(401);
  });

  test("rejects /api/overpass without an X-Trails-Session header", async ({ request }) => {
    const response = await request.post(`${PLANNER}/api/overpass`, {
      data: "data=[out:json];node[amenity=drinking_water](52.52,13.4,52.53,13.41);out;",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Origin: PLANNER,
      },
    });
    expect(response.status()).toBe(401);
  });
});
