import { afterEach, describe, expect, it } from "vitest";
import type { FastifyInstance } from "fastify";
import { buildApp } from "../src/app.js";
import type { AppConfig } from "../src/config.js";
import { CSRF_COOKIE, SESSION_COOKIE } from "../src/security.js";

const apps: FastifyInstance[] = [];

function testConfig(): AppConfig {
  return {
    nodeEnv: "test",
    host: "127.0.0.1",
    port: 8787,
    databasePath: ":memory:",
    sessionTtlMs: 60_000,
    cookieSecure: false,
    allowedOrigins: new Set(["http://mg4pi.local:8787"]),
    updateStatusPath: `/tmp/pi-car-companion-test-${process.pid}-missing-update.json`,
    versionFile: `/tmp/pi-car-companion-test-${process.pid}-missing-revision`,
    network: {
      enabled: false,
      statusPath: `/tmp/pi-car-companion-test-${process.pid}-missing-network-status.json`,
      commandPath: `/tmp/pi-car-companion-test-${process.pid}-network-command.json`,
      configurationRequestPath: `/tmp/pi-car-companion-test-${process.pid}-network-configuration.json`,
      activityPath: `/tmp/pi-car-companion-test-${process.pid}-network-activity.json`
    },
    adb: { enabled: false, executable: "adb", serial: null, timeoutMs: 3_000 }
  };
}

async function createApp(): Promise<FastifyInstance> {
  const app = await buildApp(testConfig());
  apps.push(app);
  return app;
}

async function csrf(app: FastifyInstance): Promise<string> {
  const response = await app.inject({ method: "GET", url: "/api/auth/state" });
  expect(response.statusCode).toBe(200);
  return response.json<{ csrfToken: string }>().csrfToken;
}

function mutationHeaders(token: string) {
  return {
    cookie: `${CSRF_COOKIE}=${token}`,
    "x-csrf-token": token,
    origin: "http://mg4pi.local:8787"
  };
}

async function setup(app: FastifyInstance, token: string) {
  return app.inject({
    method: "POST",
    url: "/api/auth/setup",
    headers: mutationHeaders(token),
    payload: { username: "owner", password: "Correct-horse1" }
  });
}

afterEach(async () => {
  await Promise.all(apps.splice(0).map((app) => app.close()));
});

describe("authentication boundary", () => {
  it("creates exactly one initial administrator", async () => {
    const app = await createApp();
    const token = await csrf(app);

    expect((await setup(app, token)).statusCode).toBe(201);
    const second = await app.inject({
      method: "POST",
      url: "/api/auth/setup",
      headers: mutationHeaders(token),
      payload: { username: "second", password: "Another-pass2" }
    });

    expect(second.statusCode).toBe(409);
    expect(second.json()).toMatchObject({ error: { code: "SETUP_COMPLETE" } });
  });

  it("requires 8 characters, an uppercase letter, and a number for setup", async () => {
    const app = await createApp();
    const token = await csrf(app);
    const cases = [
      { password: "Short1", expectedMessage: "at least 8 characters" },
      { password: "lowercase1", expectedMessage: "uppercase letter" },
      { password: "NoNumberHere", expectedMessage: "one number" }
    ];

    for (const testCase of cases) {
      const response = await app.inject({
        method: "POST",
        url: "/api/auth/setup",
        headers: mutationHeaders(token),
        payload: { username: "owner", password: testCase.password }
      });
      expect(response.statusCode).toBe(400);
      expect(response.json<{ error: { message: string } }>().error.message).toContain(testCase.expectedMessage);
    }
  });

  it("rejects state changes without a matching CSRF token", async () => {
    const app = await createApp();
    const response = await app.inject({
      method: "POST",
      url: "/api/auth/setup",
      payload: { username: "owner", password: "Correct-horse1" }
    });

    expect(response.statusCode).toBe(403);
    expect(response.json()).toMatchObject({ error: { code: "CSRF_REJECTED" } });
  });

  it("rejects an untrusted browser origin", async () => {
    const app = await createApp();
    const token = await csrf(app);
    const response = await app.inject({
      method: "POST",
      url: "/api/auth/setup",
      headers: { ...mutationHeaders(token), origin: "https://attacker.example" },
      payload: { username: "owner", password: "Correct-horse1" }
    });

    expect(response.statusCode).toBe(403);
    expect(response.json()).toMatchObject({ error: { code: "ORIGIN_REJECTED" } });
  });

  it("accepts a same-host origin for dynamic LAN addresses", async () => {
    const app = await createApp();
    const token = await csrf(app);
    const response = await app.inject({
      method: "POST",
      url: "/api/auth/setup",
      headers: {
        ...mutationHeaders(token),
        host: "192.168.4.20:8787",
        origin: "http://192.168.4.20:8787"
      },
      payload: { username: "owner", password: "Correct-horse1" }
    });

    expect(response.statusCode).toBe(201);
  });

  it("requires a valid session for system status", async () => {
    const app = await createApp();
    expect((await app.inject({ method: "GET", url: "/api/status" })).statusCode).toBe(401);

    const token = await csrf(app);
    await setup(app, token);
    const login = await app.inject({
      method: "POST",
      url: "/api/auth/login",
      headers: mutationHeaders(token),
      payload: { username: "owner", password: "Correct-horse1" }
    });
    expect(login.statusCode).toBe(200);
    const sessionCookie = login.cookies.find((cookie) => cookie.name === SESSION_COOKIE);
    expect(sessionCookie).toBeDefined();

    const status = await app.inject({
      method: "GET",
      url: "/api/status",
      headers: { cookie: `${SESSION_COOKIE}=${sessionCookie?.value ?? ""}` }
    });
    expect(status.statusCode, status.body).toBe(200);
    expect(status.json()).toMatchObject({
      service: { state: "healthy" },
      headUnit: { available: false, state: "disabled" }
    });

    const update = await app.inject({
      method: "POST",
      url: "/api/system/update",
      headers: {
        ...mutationHeaders(token),
        cookie: `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${sessionCookie?.value ?? ""}`
      }
    });
    expect(update.statusCode).toBe(503);
    expect(update.json()).toMatchObject({ error: { code: "UPDATES_UNAVAILABLE" } });

    const check = await app.inject({
      method: "POST",
      url: "/api/system/update/check",
      headers: {
        ...mutationHeaders(token),
        cookie: `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${sessionCookie?.value ?? ""}`
      }
    });
    expect(check.statusCode).toBe(503);
    expect(check.json()).toMatchObject({ error: { code: "UPDATES_UNAVAILABLE" } });

    const invalidPower = await app.inject({
      method: "POST",
      url: "/api/system/power",
      headers: {
        ...mutationHeaders(token),
        cookie: `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${sessionCookie?.value ?? ""}`
      },
      payload: { action: "factory-reset" }
    });
    expect(invalidPower.statusCode).toBe(400);
    expect(invalidPower.json()).toMatchObject({ error: { code: "INVALID_POWER_ACTION" } });
  });

  it("does not expose update state without authentication", async () => {
    const app = await createApp();
    const response = await app.inject({ method: "GET", url: "/api/system/update" });
    expect(response.statusCode).toBe(401);
  });

  it("keeps network status and controls behind authentication and explicit configuration", async () => {
    const app = await createApp();
    expect((await app.inject({ method: "GET", url: "/api/network" })).statusCode).toBe(401);
    expect((await app.inject({ method: "GET", url: "/api/network/activity" })).statusCode).toBe(401);

    const token = await csrf(app);
    await setup(app, token);
    const login = await app.inject({
      method: "POST",
      url: "/api/auth/login",
      headers: mutationHeaders(token),
      payload: { username: "owner", password: "Correct-horse1" }
    });
    const session = login.cookies.find((item) => item.name === SESSION_COOKIE)?.value ?? "";
    const cookie = `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${session}`;
    const status = await app.inject({ method: "GET", url: "/api/network", headers: { cookie } });
    expect(status.statusCode).toBe(200);
    expect(status.json()).toMatchObject({ supported: false, enabled: false, mode: "disabled" });
    const activity = await app.inject({ method: "GET", url: "/api/network/activity", headers: { cookie } });
    expect(activity.statusCode).toBe(200);
    expect(activity.json()).toMatchObject({ supported: false, clients: [], dnsQueries: [], flows: [] });

    const action = await app.inject({
      method: "POST",
      url: "/api/network/actions",
      headers: { ...mutationHeaders(token), cookie },
      payload: { action: "retry-upstream" }
    });
    expect(action.statusCode).toBe(503);

    const invalidConfiguration = await app.inject({
      method: "POST",
      url: "/api/network/configuration",
      headers: { ...mutationHeaders(token), cookie },
      payload: { ssid: "bad/name", password: "short" }
    });
    expect(invalidConfiguration.statusCode).toBe(400);
    expect(invalidConfiguration.json()).toMatchObject({ error: { code: "INVALID_HOTSPOT_CONFIGURATION" } });
  });

  it("protects ADB operations and persists only validated shortcuts", async () => {
    const app = await createApp();
    expect((await app.inject({ method: "GET", url: "/api/adb/packages" })).statusCode).toBe(401);
    expect((await app.inject({ method: "GET", url: "/api/adb/shortcuts" })).statusCode).toBe(401);
    expect((await app.inject({ method: "GET", url: "/api/car/telemetry" })).statusCode).toBe(401);
    expect((await app.inject({ method: "GET", url: "/api/car/history" })).statusCode).toBe(401);
    expect((await app.inject({ method: "GET", url: "/api/car/statistics" })).statusCode).toBe(401);

    const token = await csrf(app);
    expect((await app.inject({
      method: "POST",
      url: "/api/car/history/clear",
      headers: mutationHeaders(token),
      payload: { mode: "history" }
    })).statusCode).toBe(401);
    await setup(app, token);
    const login = await app.inject({
      method: "POST",
      url: "/api/auth/login",
      headers: mutationHeaders(token),
      payload: { username: "owner", password: "Correct-horse1" }
    });
    const session = login.cookies.find((item) => item.name === SESSION_COOKIE)?.value ?? "";
    const cookie = `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${session}`;
    const headers = { ...mutationHeaders(token), cookie };

    const history = await app.inject({ method: "GET", url: "/api/car/history?period=24h", headers: { cookie } });
    expect(history.statusCode).toBe(200);
    expect(history.json()).toMatchObject({ period: "24h", points: [] });
    const invalidPeriod = await app.inject({ method: "GET", url: "/api/car/history?period=forever", headers: { cookie } });
    expect(invalidPeriod.statusCode).toBe(400);

    const invalidClear = await app.inject({
      method: "POST",
      url: "/api/car/history/clear",
      headers,
      payload: { mode: "recent" }
    });
    expect(invalidClear.statusCode).toBe(400);
    expect(invalidClear.json()).toMatchObject({ error: { code: "INVALID_CLEAR_TELEMETRY_MODE" } });

    const clearHistory = await app.inject({
      method: "POST",
      url: "/api/car/history/clear",
      headers,
      payload: { mode: "history" }
    });
    expect(clearHistory.statusCode).toBe(200);
    expect(clearHistory.json()).toEqual({ mode: "history", deletedSamples: 0, deletedRollups: 0 });

    const clearAll = await app.inject({
      method: "POST",
      url: "/api/car/history/clear",
      headers,
      payload: { mode: "all" }
    });
    expect(clearAll.statusCode).toBe(200);
    expect(clearAll.json()).toEqual({ mode: "all", deletedSamples: 0, deletedRollups: 0 });

    const invalid = await app.inject({
      method: "POST",
      url: "/api/adb/shortcuts",
      headers,
      payload: { name: "Unsafe", type: "component", value: "com.example/.Main;reboot" }
    });
    expect(invalid.statusCode).toBe(400);

    const created = await app.inject({
      method: "POST",
      url: "/api/adb/shortcuts",
      headers,
      payload: { name: "Settings", type: "component", value: "com.android.settings/.Settings" }
    });
    expect(created.statusCode).toBe(201);
    const shortcutId = created.json<{ id: number }>().id;
    const shortcuts = await app.inject({ method: "GET", url: "/api/adb/shortcuts", headers: { cookie } });
    expect(shortcuts.json()).toMatchObject({ shortcuts: [{ id: shortcutId, name: "Settings" }] });

    const badApk = await app.inject({
      method: "POST",
      url: "/api/adb/install",
      headers: { ...headers, "content-type": "application/vnd.android.package-archive" },
      payload: Buffer.from("plain text")
    });
    expect(badApk.statusCode).toBe(400);
    expect(badApk.json()).toMatchObject({ error: { code: "INVALID_APK" } });

    const removed = await app.inject({ method: "DELETE", url: `/api/adb/shortcuts/${shortcutId}`, headers });
    expect(removed.statusCode).toBe(204);
  });

  it("pairs, updates, and revokes a Bluetooth mobile companion", async () => {
    const app = await createApp();
    const csrfToken = await csrf(app);
    await setup(app, csrfToken);
    const login = await app.inject({
      method: "POST",
      url: "/api/auth/login",
      headers: mutationHeaders(csrfToken),
      payload: { username: "owner", password: "Correct-horse1" }
    });
    const session = login.cookies.find((item) => item.name === SESSION_COOKIE)?.value ?? "";
    const cookie = `${CSRF_COOKIE}=${csrfToken}; ${SESSION_COOKIE}=${session}`;
    const webHeaders = { ...mutationHeaders(csrfToken), cookie };

    expect((await app.inject({ method: "GET", url: "/api/mobile/devices" })).statusCode).toBe(401);
    expect((await app.inject({ method: "GET", url: "/api/mobile/bluetooth" })).statusCode).toBe(401);
    expect((await app.inject({ method: "GET", url: "/api/trips" })).statusCode).toBe(401);
    const bluetooth = await app.inject({ method: "GET", url: "/api/mobile/bluetooth", headers: { cookie } });
    expect(bluetooth.statusCode).toBe(200);
    expect(bluetooth.json()).toMatchObject({ powered: expect.any(Boolean), discoverable: expect.any(Boolean) });
    const invalidBluetoothAction = await app.inject({
      method: "POST",
      url: "/api/mobile/bluetooth",
      headers: webHeaders,
      payload: { action: "arbitrary-command" }
    });
    expect(invalidBluetoothAction.statusCode).toBe(400);
    expect(invalidBluetoothAction.json()).toMatchObject({ error: { code: "INVALID_BLUETOOTH_ACTION" } });
    const pairing = await app.inject({ method: "POST", url: "/api/mobile/pairing", headers: webHeaders });
    expect(pairing.statusCode).toBe(200);
    const code = pairing.json<{ code: string }>().code;
    expect(code).toMatch(/^\d{6}$/);

    const deviceId = "2f9ca5d6-28cd-45a7-a7f5-27a13dc9eb98";
    const paired = await app.inject({
      method: "POST",
      url: "/internal/mobile/pair",
      payload: { code, deviceId, deviceName: "Owner phone" }
    });
    expect(paired.statusCode).toBe(200);
    const mobileToken = paired.json<{ token: string }>().token;
    const mobileHeaders = { "x-mobile-token": mobileToken };

    const location = await app.inject({
      method: "POST",
      url: "/internal/mobile/location",
      headers: mobileHeaders,
      payload: {
        capturedAt: "2026-07-31T20:00:00.000Z",
        latitude: 55.6761,
        longitude: 12.5683,
        accuracyMeters: 4.2,
        speedKph: 42.5,
        batteryPercent: 76,
        networkType: "cellular"
      }
    });
    expect(location.statusCode).toBe(200);

    const snapshot = await app.inject({ method: "GET", url: "/internal/mobile/snapshot", headers: mobileHeaders });
    expect(snapshot.statusCode).toBe(200);
    expect(snapshot.json()).toMatchObject({
      protocolVersion: 1,
      phone: { latitude: 55.6761, speedKph: 42.5, networkType: "cellular" },
      shortcuts: []
    });

    const trips = await app.inject({ method: "GET", url: "/api/trips", headers: { cookie } });
    expect(trips.statusCode).toBe(200);
    const trip = trips.json<{ trips: Array<{ id: number; peakSpeedKph: number; pointCount: number }> }>().trips[0];
    expect(trip).toMatchObject({ peakSpeedKph: 42.5, pointCount: 1 });
    const tripDetail = await app.inject({ method: "GET", url: `/api/trips/${trip!.id}`, headers: { cookie } });
    expect(tripDetail.statusCode).toBe(200);
    expect(tripDetail.json()).toMatchObject({
      points: [expect.objectContaining({ latitude: 55.6761, longitude: 12.5683 })],
      pins: expect.arrayContaining([expect.objectContaining({ type: "peak-speed", speedKph: 42.5 })])
    });

    const devices = await app.inject({ method: "GET", url: "/api/mobile/devices", headers: { cookie } });
    expect(devices.json()).toMatchObject({ devices: [{ id: deviceId, name: "Owner phone", revokedAt: null }] });
    expect((await app.inject({ method: "DELETE", url: `/api/mobile/devices/${deviceId}`, headers: webHeaders })).statusCode).toBe(204);
    expect((await app.inject({ method: "GET", url: "/internal/mobile/snapshot", headers: mobileHeaders })).statusCode).toBe(401);
  });

  it("exposes only allowlisted jobs and authenticated run history", async () => {
    const app = await createApp();
    const token = await csrf(app);
    await setup(app, token);
    const login = await app.inject({
      method: "POST",
      url: "/api/auth/login",
      headers: mutationHeaders(token),
      payload: { username: "owner", password: "Correct-horse1" }
    });
    const session = login.cookies.find((item) => item.name === SESSION_COOKIE)?.value ?? "";
    const cookie = `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${session}`;

    expect((await app.inject({ method: "GET", url: "/api/jobs" })).statusCode).toBe(401);
    const jobs = await app.inject({ method: "GET", url: "/api/jobs", headers: { cookie } });
    expect(jobs.statusCode).toBe(200);
    expect(jobs.json<{ jobs: { id: string }[] }>().jobs.map((job) => job.id)).toEqual([
      "refresh-health",
      "network-diagnostics",
      "support-bundle"
    ]);

    const unknown = await app.inject({
      method: "POST",
      url: "/api/jobs/arbitrary-shell/runs",
      headers: { ...mutationHeaders(token), cookie }
    });
    expect(unknown.statusCode).toBe(404);
    expect(unknown.json()).toMatchObject({ error: { code: "JOB_NOT_FOUND" } });

    const queued = await app.inject({
      method: "POST",
      url: "/api/jobs/refresh-health/runs",
      headers: { ...mutationHeaders(token), cookie }
    });
    expect(queued.statusCode).toBe(202);
    const runId = queued.json<{ id: string }>().id;
    let run: { status: string } = { status: "queued" };
    for (let attempt = 0; attempt < 50 && ["queued", "running"].includes(run.status); attempt += 1) {
      await new Promise((resolve) => setTimeout(resolve, 2));
      const response = await app.inject({ method: "GET", url: `/api/job-runs/${runId}`, headers: { cookie } });
      expect(response.statusCode).toBe(200);
      run = response.json<{ status: string }>();
    }
    expect(run.status).toBe("succeeded");
  });
});
