/**
 * Generates TankTrack_Postman_Collection.json (Postman v2.1) from route definitions.
 * Run: npm run postman:generate
 */
import * as fs from "fs";
import * as path from "path";

type Auth = "none" | "bearer" | "static" | "admin" | "optional";

interface QueryParam {
  key: string;
  value: string;
  description?: string;
  disabled?: boolean;
}

interface ReqDef {
  name: string;
  method: string;
  /** Path after /api/v1, e.g. auth/login */
  path: string;
  auth?: Auth;
  body?: string;
  description?: string;
  query?: QueryParam[];
  formdata?: Array<{ key: string; value: string; type?: string }>;
  testScript?: string[];
}

function headers(auth?: Auth): Array<{ key: string; value: string }> {
  const h: Array<{ key: string; value: string }> = [];
  if (auth === "static") {
    h.push({ key: "auth-token", value: "{{static_auth_token}}" });
  }
  if (auth === "bearer" || auth === "optional") {
    h.push({ key: "Authorization", value: "Bearer {{token}}" });
  }
  if (auth === "admin") {
    h.push({ key: "Authorization", value: "Bearer {{admin_token}}" });
  }
  if (["POST", "PUT", "PATCH"].includes("POST") && auth !== "none") {
    // content-type added per request when body exists
  }
  return h;
}

function buildRequest(def: ReqDef): Record<string, unknown> {
  const hdrs = headers(def.auth);
  const req: Record<string, unknown> = {
    method: def.method,
    header: hdrs,
    description: def.description ?? "",
  };

  if (def.query && def.query.length > 0) {
    const segments = def.path.split("/").filter(Boolean);
    req.url = {
      raw: `{{apiUrl}}/${def.path}?${def.query.map((q) => `${q.key}=${encodeURIComponent(q.value)}`).join("&")}`,
      host: ["{{apiUrl}}"],
      path: segments,
      query: def.query,
    };
  } else if (def.path.includes("?")) {
    req.url = `{{apiUrl}}/${def.path}`;
  } else {
    req.url = `{{apiUrl}}/${def.path}`;
  }

  if (def.body) {
    hdrs.push({ key: "Content-Type", value: "application/json" });
    req.body = { mode: "raw", raw: def.body };
  }
  if (def.formdata) {
    req.body = { mode: "formdata", formdata: def.formdata };
  }

  const item: Record<string, unknown> = { name: def.name, request: req };
  if (def.testScript?.length) {
    item.event = [
      {
        listen: "test",
        script: { type: "text/javascript", exec: def.testScript },
      },
    ];
  }
  return item;
}

function folder(
  name: string,
  description: string,
  items: ReqDef[],
): Record<string, unknown> {
  return {
    name,
    description,
    item: items.map(buildRequest),
  };
}

const saveFuelIdScript = [
  "const body = pm.response.json();",
  "const data = body.data || {};",
  "if (data._id) pm.collectionVariables.set('fuelRequestId', String(data._id));",
  "const list = data.data;",
  "if (Array.isArray(list)) {",
  "  const p = list.find(r => r.status === 'pending') || list[0];",
  "  if (p && p._id) pm.collectionVariables.set('fuelRequestId', String(p._id));",
  "}",
];

const saveFriendIdScript = [
  "const body = pm.response.json();",
  "const list = (body.data && body.data.data) || [];",
  "if (list[0] && list[0]._id) pm.collectionVariables.set('targetUserId', String(list[0]._id));",
];

const collection = {
  info: {
    name: "Tank Track API",
    _postman_id: "f78f2471-f29e-45de-9a64-b8668025f58e",
    description:
      "Complete Postman Collection v2.1 for Tank Track API.\n\n" +
      "**Setup:** `baseUrl` = http://localhost:6260, `static_auth_token` = BEARER_TOKEN from .env\n\n" +
      "**Auth:** Run **Auth → Login** — saves `token` + `userId`\n\n" +
      "**Protected:** `Authorization: Bearer {{token}}`\n\n" +
      "**Public auth:** `auth-token: {{static_auth_token}}`\n\n" +
      "**Modules:** Auth, Users, Connections, Fuel Requests, Vehicles, Trips, Gas Stations, Smartcar, Wallet, Billing, Webhooks, Admin, Public",
    schema:
      "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
  },
  variable: [
    { key: "baseUrl", value: "http://localhost:6260", type: "string" },
    { key: "apiUrl", value: "{{baseUrl}}/api/v1", type: "string" },
    { key: "token", value: "", type: "string", description: "JWT" },
    { key: "admin_token", value: "", type: "string" },
    {
      key: "static_auth_token",
      value: "ab6410c710c7ce43c36e37084a4b5205b0e1608477336023a8520c9f104398f9",
      type: "string",
      description: "BEARER_TOKEN from .env",
    },
    { key: "login_email", value: "jack@yopmail.com", type: "string" },
    { key: "login_password", value: "Password123", type: "string" },
    { key: "receiver_email", value: "jim@yopmail.com", type: "string" },
    { key: "receiver_password", value: "Password123", type: "string" },
    { key: "receiver_token", value: "", type: "string" },
    { key: "admin_email", value: "admin@example.com", type: "string" },
    { key: "admin_password", value: "admin12345", type: "string" },
    { key: "userId", value: "", type: "string" },
    {
      key: "targetUserId",
      value: "",
      type: "string",
      description: "Friend _id for unfriend + fuel",
    },
    {
      key: "receiverUserId",
      value: "",
      type: "string",
      description: "Alias for fuel receiver",
    },
    { key: "invite_email", value: "friend@example.com", type: "string" },
    { key: "connectionRequestId", value: "", type: "string" },
    { key: "fuelRequestId", value: "", type: "string" },
    { key: "amountCents", value: "500", type: "string" },
    { key: "vehicleId", value: "", type: "string" },
    { key: "tripId", value: "", type: "string" },
    { key: "gasStationId", value: "", type: "string" },
    { key: "placeId", value: "ChIJN1t_tDeuEmsRUsoyG83frY4", type: "string" },
    { key: "paymentIntentId", value: "", type: "string" },
    { key: "paymentMethodId", value: "", type: "string" },
    { key: "device_token", value: "postman-device", type: "string" },
    { key: "feedbackId", value: "", type: "string" },
    { key: "planId", value: "", type: "string" },
    { key: "contentSection", value: "privacy_policy", type: "string" },
    { key: "smartcar_webhook_id", value: "", type: "string" },
    { key: "revenuecat_webhook_secret", value: "", type: "string" },
    {
      key: "wallet_stripe_return_url",
      value: "{{apiUrl}}/user/stripe/return",
      type: "string",
    },
    {
      key: "wallet_stripe_refresh_url",
      value: "{{apiUrl}}/user/stripe/refresh",
      type: "string",
    },
    {
      key: "gas_station_stripe_return_url",
      value: "{{apiUrl}}/gas-stations/stripe/return",
      type: "string",
    },
    {
      key: "gas_station_stripe_refresh_url",
      value: "{{apiUrl}}/gas-stations/stripe/refresh",
      type: "string",
    },
  ],
  event: [
    {
      listen: "test",
      script: {
        type: "text/javascript",
        exec: [
          "(function saveAuth() {",
          "  try {",
          "    if (!pm.response || pm.response.code === 0) return;",
          "    const url = pm.request.url.toString();",
          "    const authPaths = /\\/(auth\\/(login|signup|verify-otp|social-login|auto-login)|admin\\/login|gas-stations\\/(account\\/(verify-otp|login)|login))/i;",
          "    if (!authPaths.test(url)) return;",
          "    let json; try { json = pm.response.json(); } catch (e) { return; }",
          "    const data = json && json.data;",
          "    if (!data) return;",
          "    const isAdmin = /\\/admin\\/login/i.test(url);",
          "    const token = data.token;",
          "    let userId = data._id || data.id || data.userId;",
          "    if (data.user) userId = userId || data.user._id || data.user.id;",
          "    if (token) pm.collectionVariables.set(isAdmin ? 'admin_token' : 'token', token);",
          "    if (userId) pm.collectionVariables.set('userId', String(userId));",
          "    if (data.gasStation && data.gasStation._id) pm.collectionVariables.set('gasStationId', String(data.gasStation._id));",
          "  } catch (e) {}",
          "})();",
          "(function saveConnectionIds() {",
          "  try {",
          "    if (!/\\/connections\\/requests/i.test(pm.request.url.toString())) return;",
          "    const json = pm.response.json();",
          "    const items = json.data && json.data.data;",
          "    if (items && items[0] && items[0].requestId) pm.collectionVariables.set('connectionRequestId', String(items[0].requestId));",
          "  } catch (e) {}",
          "})();",
          "(function saveFuelId() {",
          "  try {",
          "    const url = pm.request.url.toString();",
          "    if (!/fuel-requests/i.test(url) || pm.response.code !== 200) return;",
          "    const json = pm.response.json();",
          "    const data = json.data || {};",
          "    if (data._id) pm.collectionVariables.set('fuelRequestId', String(data._id));",
          "    const list = data.data;",
          "    if (Array.isArray(list)) {",
          "      const p = list.find(r => r.status === 'pending') || list[0];",
          "      if (p && p._id) pm.collectionVariables.set('fuelRequestId', String(p._id));",
          "    }",
          "  } catch (e) {}",
          "})();",
        ],
      },
    },
  ],
  item: [
    folder("Auth", "Public routes need auth-token header.", [
      {
        name: "Signup",
        method: "POST",
        path: "auth/signup",
        auth: "static",
        body: '{\n  "email": "{{login_email}}",\n  "password": "{{login_password}}"\n}',
      },
      {
        name: "Login",
        method: "POST",
        path: "auth/login",
        auth: "static",
        body: '{\n  "email": "{{login_email}}",\n  "password": "{{login_password}}",\n  "device": { "device_token": "{{device_token}}", "device_type": "android" }\n}',
        description: "Saves token + userId via collection test script.",
      },
      {
        name: "Verify OTP",
        method: "POST",
        path: "auth/verify-otp",
        auth: "static",
        body: '{\n  "userId": "{{userId}}",\n  "otp": "123456"\n}',
      },
      {
        name: "Send OTP",
        method: "POST",
        path: "auth/send-otp",
        auth: "static",
        body: '{\n  "email": "{{login_email}}",\n  "reason": "registration"\n}',
      },
      {
        name: "Forgot password",
        method: "POST",
        path: "auth/forgot-password",
        auth: "static",
        body: '{\n  "email": "{{login_email}}"\n}',
      },
      {
        name: "Change password (logged-in)",
        method: "POST",
        path: "auth/change-password",
        auth: "bearer",
        body: '{\n  "oldPassword": "oldPass123",\n  "newPassword": "newPass123"\n}',
      },
      {
        name: "Change password (mobile reset)",
        method: "POST",
        path: "auth/changePassword",
        auth: "bearer",
        body: '{\n  "password": "newPass123",\n  "confirm_password": "newPass123"\n}',
      },
      {
        name: "Social login",
        method: "POST",
        path: "auth/social-login",
        auth: "static",
        body: '{\n  "role": "USER",\n  "accessToken": "google-id-token",\n  "provider": "google"\n}',
      },
      {
        name: "Auto login",
        method: "POST",
        path: "auth/auto-login",
        auth: "bearer",
      },
      { name: "Logout", method: "POST", path: "auth/logout", auth: "bearer" },
      {
        name: "Update profile",
        method: "POST",
        path: "auth/update-profile",
        auth: "bearer",
        formdata: [
          { key: "fullName", value: "John Doe", type: "text" },
          { key: "type", value: "update", type: "text" },
        ],
      },
      {
        name: "Delete account",
        method: "GET",
        path: "auth/delete-account",
        auth: "bearer",
      },
    ]),
    folder("Users", "Authenticated user profile + wallet aliases.", [
      {
        name: "View profile",
        method: "GET",
        path: "user/viewUserProfile",
        auth: "bearer",
      },
      {
        name: "Change password",
        method: "POST",
        path: "user/changePassword",
        auth: "bearer",
        body: '{\n  "password": "newPass123",\n  "confirm_password": "newPass123"\n}',
      },
      {
        name: "Connect Stripe",
        method: "POST",
        path: "user/connect-stripe",
        auth: "bearer",
        body: '{\n  "returnUrl": "{{wallet_stripe_return_url}}",\n  "refreshUrl": "{{wallet_stripe_refresh_url}}"\n}',
      },
      {
        name: "Refresh Stripe status",
        method: "POST",
        path: "user/refresh-stripe-status",
        auth: "bearer",
      },
      {
        name: "Wallet top-up intent",
        method: "POST",
        path: "user/wallet/top-up/intent",
        auth: "bearer",
        body: '{\n  "amountCents": 1000,\n  "currency": "usd"\n}',
      },
      {
        name: "Wallet top-up reconcile",
        method: "POST",
        path: "user/wallet/top-up/reconcile",
        auth: "bearer",
        body: '{\n  "paymentIntentId": "{{paymentIntentId}}"\n}',
      },
      {
        name: "Stripe return (browser)",
        method: "GET",
        path: "user/stripe/return?uid={{userId}}",
        auth: "none",
      },
      {
        name: "Stripe refresh (browser)",
        method: "GET",
        path: "user/stripe/refresh?uid={{userId}}",
        auth: "none",
      },
      {
        name: "Delete car (alias)",
        method: "DELETE",
        path: "user/car/{{vehicleId}}/delete",
        auth: "bearer",
      },
    ]),
    folder(
      "Connections",
      "Friends module. Unfriend uses friend's user _id (targetUserId).",
      [
        {
          name: "Send invite / request",
          method: "POST",
          path: "connections/invite",
          auth: "bearer",
          body: '{\n  "email": "{{invite_email}}"\n}',
        },
        {
          name: "Nearby users",
          method: "GET",
          path: "connections/nearby-users",
          auth: "bearer",
          query: [
            { key: "latitude", value: "37.7749" },
            { key: "longitude", value: "-122.4194" },
            { key: "radius", value: "5" },
            { key: "page", value: "1" },
            { key: "limit", value: "20" },
          ],
        },
        {
          name: "My connections",
          method: "GET",
          path: "connections/my-connections",
          auth: "bearer",
          query: [
            { key: "page", value: "1" },
            { key: "limit", value: "20" },
          ],
          testScript: saveFriendIdScript,
        },
        {
          name: "Requests received",
          method: "GET",
          path: "connections/requests",
          auth: "bearer",
          query: [
            { key: "type", value: "received" },
            { key: "page", value: "1" },
            { key: "limit", value: "20" },
          ],
        },
        {
          name: "Requests sent",
          method: "GET",
          path: "connections/requests",
          auth: "bearer",
          query: [
            { key: "type", value: "sent" },
            { key: "page", value: "1" },
            { key: "limit", value: "20" },
          ],
        },
        {
          name: "Accept request",
          method: "PATCH",
          path: "connections/{{connectionRequestId}}/accept",
          auth: "bearer",
        },
        {
          name: "Reject request",
          method: "PATCH",
          path: "connections/{{connectionRequestId}}/reject",
          auth: "bearer",
        },
        {
          name: "Cancel request",
          method: "PATCH",
          path: "connections/{{connectionRequestId}}/cancel",
          auth: "bearer",
        },
        {
          name: "Remove connection (unfriend)",
          method: "DELETE",
          path: "connections/{{targetUserId}}",
          auth: "bearer",
          description: "Use friend's user _id from My Connections.",
        },
      ],
    ),
    folder(
      "Fuel Requests",
      "Requires accepted connection. amountCents in USD cents (500 = $5). Transfer uses receiver wallet.",
      [
        {
          name: "Send fuel request",
          method: "POST",
          path: "fuel-requests",
          auth: "bearer",
          body: '{\n  "receiverUserId": "{{receiverUserId}}",\n  "amountCents": {{amountCents}},\n  "message": "Need fuel help"\n}',
          testScript: saveFuelIdScript,
        },
        {
          name: "Sent fuel requests",
          method: "GET",
          path: "fuel-requests/sent",
          auth: "bearer",
          query: [
            { key: "page", value: "1" },
            { key: "limit", value: "20" },
          ],
        },
        {
          name: "Received fuel requests",
          method: "GET",
          path: "fuel-requests/received",
          auth: "bearer",
          query: [
            { key: "page", value: "1" },
            { key: "limit", value: "20" },
          ],
          testScript: saveFuelIdScript,
        },
        {
          name: "Transfer (accept & pay)",
          method: "PATCH",
          path: "fuel-requests/{{fuelRequestId}}/transfer",
          auth: "bearer",
          description: "Receiver pays — debit wallet, credit sender.",
        },
        {
          name: "Reject fuel request",
          method: "PATCH",
          path: "fuel-requests/{{fuelRequestId}}/reject",
          auth: "bearer",
        },
      ],
    ),
    folder("Vehicles", "", [
      {
        name: "Get all vehicles",
        method: "GET",
        path: "vehicles/getAllVehicles",
        auth: "bearer",
      },
      {
        name: "Add vehicle",
        method: "POST",
        path: "vehicles/addVehicle",
        auth: "bearer",
        body: '{\n  "name": "Honda Civic",\n  "vehicleModel": "Civic 2020",\n  "manufacturingYear": "2020",\n  "tankCapacity": "12",\n  "currentMPG": "30"\n}',
      },
      {
        name: "Get vehicle by ID",
        method: "GET",
        path: "vehicles/{{vehicleId}}",
        auth: "bearer",
      },
      {
        name: "Delete vehicle",
        method: "DELETE",
        path: "vehicles/{{vehicleId}}",
        auth: "bearer",
      },
    ]),
    folder("Trips", "", [
      {
        name: "Calculate metrics",
        method: "POST",
        path: "trips/calculate-metrics",
        auth: "bearer",
        body: '{\n  "startOdometer": 10000,\n  "endOdometer": 10150,\n  "fuelUsed": 5.2\n}',
      },
      {
        name: "Calculate metrics by name",
        method: "POST",
        path: "trips/calculate-metrics-by-name",
        auth: "bearer",
        body: '{\n  "vehicleName": "Honda Civic",\n  "distanceMiles": 50\n}',
      },
      {
        name: "Add trip (multipart)",
        method: "POST",
        path: "trips/addTrip",
        auth: "bearer",
        formdata: [
          { key: "vehicleId", value: "{{vehicleId}}", type: "text" },
          { key: "tripName", value: "Weekend drive", type: "text" },
        ],
      },
      {
        name: "Get all trips",
        method: "GET",
        path: "trips/getAllTrips",
        auth: "bearer",
      },
      {
        name: "Get trip by ID",
        method: "GET",
        path: "trips/{{tripId}}",
        auth: "bearer",
      },
      {
        name: "Update trip (multipart)",
        method: "PUT",
        path: "trips/{{tripId}}",
        auth: "bearer",
        formdata: [{ key: "tripName", value: "Updated trip", type: "text" }],
      },
      {
        name: "Update trip status",
        method: "PATCH",
        path: "trips/{{tripId}}/status",
        auth: "bearer",
        body: '{\n  "status": "completed"\n}',
      },
      {
        name: "Delete trip",
        method: "DELETE",
        path: "trips/{{tripId}}",
        auth: "bearer",
      },
    ]),
    folder("Gas Stations", "", [
      {
        name: "Account signup",
        method: "POST",
        path: "gas-stations/account/signup",
        auth: "none",
        body: '{\n  "email": "owner@example.com",\n  "password": "Password123"\n}',
      },
      {
        name: "Account verify OTP",
        method: "POST",
        path: "gas-stations/account/verify-otp",
        auth: "none",
        body: '{\n  "userId": "{{userId}}",\n  "otp": "123456"\n}',
      },
      {
        name: "Account resend OTP",
        method: "POST",
        path: "gas-stations/account/resend-otp",
        auth: "none",
        body: '{\n  "userId": "{{userId}}"\n}',
      },
      {
        name: "Account login",
        method: "POST",
        path: "gas-stations/account/login",
        auth: "none",
        body: '{\n  "email": "owner@example.com",\n  "password": "Password123"\n}',
      },
      {
        name: "Forgot password",
        method: "POST",
        path: "gas-stations/account/forgot-password",
        auth: "none",
        body: '{\n  "email": "owner@example.com"\n}',
      },
      {
        name: "Verify reset OTP",
        method: "POST",
        path: "gas-stations/account/verify-reset-otp",
        auth: "none",
        body: '{\n  "userId": "{{userId}}",\n  "otp": "123456"\n}',
      },
      {
        name: "Reset password",
        method: "POST",
        path: "gas-stations/account/reset-password",
        auth: "none",
        body: '{\n  "userId": "{{userId}}",\n  "otp": "123456",\n  "password": "NewPass123",\n  "confirm_password": "NewPass123"\n}',
      },
      {
        name: "Login (legacy)",
        method: "POST",
        path: "gas-stations/login",
        auth: "none",
        body: '{\n  "email": "owner@example.com",\n  "password": "Password123"\n}',
      },
      {
        name: "Register with account (multipart)",
        method: "POST",
        path: "gas-stations/register-with-account",
        auth: "none",
        description:
          "Creates account + station with approvalStatus=pending, isAdminApproved=false. FE: waiting screen until admin approves.",
        formdata: [
          { key: "email", value: "owner@example.com", type: "text" },
          { key: "password", value: "Password123", type: "text" },
          { key: "stationName", value: "My Gas Station", type: "text" },
        ],
      },
      {
        name: "Register station (auth + multipart)",
        method: "POST",
        path: "gas-stations/register",
        auth: "bearer",
        description:
          "Registers station as pending. Response includes approvalStatus + isAdminApproved for FE routing.",
        formdata: [
          { key: "stationName", value: "My Gas Station", type: "text" },
          { key: "address", value: "123 Main St", type: "text" },
        ],
      },
      {
        name: "Update station (multipart)",
        method: "PUT",
        path: "gas-stations/update",
        auth: "bearer",
        formdata: [
          { key: "stationName", value: "Updated Station", type: "text" },
        ],
      },
      {
        name: "Upload station media",
        method: "POST",
        path: "gas-stations/upload-media",
        auth: "bearer",
        formdata: [
          { key: "mainImage", value: "", type: "file" },
          { key: "logo", value: "", type: "file" },
        ],
      },
      {
        name: "My station",
        method: "GET",
        path: "gas-stations/my-station",
        auth: "bearer",
      },
      {
        name: "My dashboard",
        method: "GET",
        path: "gas-stations/my-dashboard",
        auth: "bearer",
      },
      {
        name: "Connect Stripe",
        method: "POST",
        path: "gas-stations/connect-stripe",
        auth: "bearer",
        body: '{\n  "returnUrl": "{{gas_station_stripe_return_url}}",\n  "refreshUrl": "{{gas_station_stripe_refresh_url}}"\n}',
      },
      {
        name: "Refresh Stripe status",
        method: "POST",
        path: "gas-stations/refresh-stripe-status",
        auth: "bearer",
      },
      {
        name: "Stripe return",
        method: "GET",
        path: "gas-stations/stripe/return?uid={{userId}}",
        auth: "none",
      },
      {
        name: "Stripe refresh",
        method: "GET",
        path: "gas-stations/stripe/refresh?uid={{userId}}",
        auth: "none",
      },
      {
        name: "Nearest stations",
        method: "GET",
        path: "gas-stations/nearest",
        auth: "bearer",
        query: [
          { key: "lat", value: "37.7749" },
          { key: "lng", value: "-122.4194" },
          { key: "radius", value: "50" },
          { key: "source", value: "both" },
        ],
      },
      {
        name: "List gas stations",
        method: "GET",
        path: "gas-stations",
        auth: "bearer",
        query: [
          { key: "page", value: "1" },
          { key: "limit", value: "20" },
        ],
      },
      {
        name: "Registered station by ID",
        method: "GET",
        path: "gas-stations/registered/{{gasStationId}}",
        auth: "bearer",
      },
      {
        name: "Station details (Google placeId)",
        method: "GET",
        path: "gas-stations/{{placeId}}",
        auth: "bearer",
      },
    ]),
    folder("Smartcar", "", [
      { name: "Ping", method: "GET", path: "smartcar/ping", auth: "none" },
      {
        name: "Login (get OAuth URL)",
        method: "GET",
        path: "smartcar/login",
        auth: "bearer",
      },
      {
        name: "Complete connect (JWT + code)",
        method: "POST",
        path: "smartcar/complete-connect",
        auth: "bearer",
        body: '{\n  "code": "auth-code-from-smartcar"\n}',
      },
      {
        name: "OAuth redirect",
        method: "GET",
        path: "smartcar/redirect",
        auth: "none",
      },
      {
        name: "OAuth callback",
        method: "GET",
        path: "smartcar/callback",
        auth: "none",
      },
      {
        name: "OAuth done",
        method: "GET",
        path: "smartcar/oauth-done",
        auth: "none",
      },
      {
        name: "List vehicles",
        method: "GET",
        path: "smartcar/vehicles",
        auth: "bearer",
      },
      {
        name: "List vehicles (sync)",
        method: "GET",
        path: "smartcar/vehicles",
        auth: "bearer",
        query: [{ key: "sync", value: "true" }],
      },
      {
        name: "Vehicle live data",
        method: "GET",
        path: "smartcar/vehicle/{{vehicleId}}",
        auth: "bearer",
      },
      {
        name: "Subscribe vehicle webhook",
        method: "POST",
        path: "smartcar/vehicle/{{vehicleId}}/subscribe-webhook",
        auth: "bearer",
        body: '{\n  "webhookId": "{{smartcar_webhook_id}}"\n}',
      },
      {
        name: "Disconnect",
        method: "POST",
        path: "smartcar/disconnect",
        auth: "bearer",
      },
      {
        name: "Status",
        method: "GET",
        path: "smartcar/status",
        auth: "bearer",
      },
    ]),
    folder("Wallet", "", [
      { name: "Get balance", method: "GET", path: "wallet", auth: "bearer" },
      {
        name: "List transactions",
        method: "GET",
        path: "wallet/transactions",
        auth: "bearer",
        query: [
          { key: "page", value: "1" },
          { key: "limit", value: "20" },
        ],
      },
      {
        name: "List payment methods",
        method: "GET",
        path: "wallet/payment-methods",
        auth: "bearer",
      },
      {
        name: "Detach payment method",
        method: "DELETE",
        path: "wallet/payment-methods/{{paymentMethodId}}",
        auth: "bearer",
      },
      {
        name: "Top-up intent",
        method: "POST",
        path: "wallet/top-up/intent",
        auth: "bearer",
        body: '{\n  "amountCents": 1000,\n  "currency": "usd"\n}',
      },
      {
        name: "Top-up reconcile",
        method: "POST",
        path: "wallet/top-up/reconcile",
        auth: "bearer",
        body: '{\n  "paymentIntentId": "{{paymentIntentId}}"\n}',
      },
      {
        name: "Reconcile balance",
        method: "POST",
        path: "wallet/reconcile-balance",
        auth: "bearer",
      },
      {
        name: "Withdraw",
        method: "POST",
        path: "wallet/withdraw",
        auth: "bearer",
        body: '{\n  "amountCents": 500,\n  "note": "Payout"\n}',
      },
      {
        name: "Connect Stripe",
        method: "POST",
        path: "wallet/connect-stripe",
        auth: "bearer",
        body: '{\n  "returnUrl": "{{wallet_stripe_return_url}}",\n  "refreshUrl": "{{wallet_stripe_refresh_url}}"\n}',
      },
      {
        name: "Refresh Stripe status",
        method: "POST",
        path: "wallet/refresh-stripe-status",
        auth: "bearer",
      },
      {
        name: "Stripe return",
        method: "GET",
        path: "wallet/stripe/return?uid={{userId}}",
        auth: "none",
      },
      {
        name: "Stripe refresh",
        method: "GET",
        path: "wallet/stripe/refresh?uid={{userId}}",
        auth: "none",
      },
    ]),
    folder("Billing", "", [
      {
        name: "List plans (public)",
        method: "GET",
        path: "billing/plans",
        auth: "none",
      },
      {
        name: "My subscription",
        method: "GET",
        path: "billing/me",
        auth: "bearer",
      },
      {
        name: "Billing history",
        method: "GET",
        path: "billing/history",
        auth: "bearer",
        query: [
          { key: "page", value: "1" },
          { key: "limit", value: "20" },
        ],
      },
      {
        name: "RevenueCat sync",
        method: "POST",
        path: "billing/revenuecat/sync",
        auth: "bearer",
      },
    ]),
    folder("Webhooks", "Server-to-server only — not for mobile.", [
      {
        name: "Stripe wallet webhook",
        method: "POST",
        path: "wallet/stripe-webhook",
        auth: "none",
        body: '{\n  "type": "payment_intent.succeeded"\n}',
        description: "Requires raw body + Stripe-Signature in production.",
      },
      {
        name: "Smartcar vehicle webhook",
        method: "POST",
        path: "smartcar/webhook",
        auth: "none",
        body: '{\n  "eventId": "evt-123",\n  "eventType": "verify"\n}',
      },
      {
        name: "RevenueCat webhook",
        method: "POST",
        path: "revenuecat/webhook",
        auth: "none",
        body: '{\n  "api_version": "1.0",\n  "event": { "type": "TEST" }\n}',
      },
    ]),
    folder("Admin", "Run Admin login first.", [
      {
        name: "Admin login",
        method: "POST",
        path: "admin/login",
        auth: "none",
        body: '{\n  "email": "{{admin_email}}",\n  "password": "{{admin_password}}"\n}',
      },
      {
        name: "Pending gas stations",
        method: "GET",
        path: "admin/gas-stations/pending",
        auth: "admin",
      },
      {
        name: "All gas stations",
        method: "GET",
        path: "admin/gas-stations",
        auth: "admin",
      },
      {
        name: "Gas station by ID",
        method: "GET",
        path: "admin/gas-stations/{{gasStationId}}",
        auth: "admin",
      },
      {
        name: "Approve gas station",
        method: "POST",
        path: "admin/gas-stations/{{gasStationId}}/approve",
        auth: "admin",
      },
      {
        name: "Reject gas station",
        method: "POST",
        path: "admin/gas-stations/{{gasStationId}}/reject",
        auth: "admin",
      },
      { name: "List users", method: "GET", path: "admin/users", auth: "admin" },
      {
        name: "Get user",
        method: "GET",
        path: "admin/users/{{targetUserId}}",
        auth: "admin",
      },
      {
        name: "Update user",
        method: "PATCH",
        path: "admin/users/{{targetUserId}}",
        auth: "admin",
        body: '{\n  "isBanned": false\n}',
      },
      {
        name: "Delete user",
        method: "DELETE",
        path: "admin/users/{{targetUserId}}",
        auth: "admin",
      },
      {
        name: "Reset user password",
        method: "POST",
        path: "admin/users/{{targetUserId}}/reset-password",
        auth: "admin",
        body: '{\n  "password": "TempPass123"\n}',
      },
      { name: "List trips", method: "GET", path: "admin/trips", auth: "admin" },
      {
        name: "Upcoming trips",
        method: "GET",
        path: "admin/trips/upcoming",
        auth: "admin",
      },
      {
        name: "Low fuel reminders",
        method: "GET",
        path: "admin/trips/low-fuel-reminders",
        auth: "admin",
      },
      {
        name: "Get trip",
        method: "GET",
        path: "admin/trips/{{tripId}}",
        auth: "admin",
      },
      {
        name: "Trip tracking",
        method: "GET",
        path: "admin/trips/{{tripId}}/tracking",
        auth: "admin",
      },
      {
        name: "Update trip",
        method: "PATCH",
        path: "admin/trips/{{tripId}}",
        auth: "admin",
        body: '{\n  "status": "completed"\n}',
      },
      {
        name: "Delete trip",
        method: "DELETE",
        path: "admin/trips/{{tripId}}",
        auth: "admin",
      },
      {
        name: "Vehicle fuel metrics",
        method: "GET",
        path: "admin/vehicles/fuel-metrics",
        auth: "admin",
        query: [
          { key: "page", value: "1" },
          { key: "limit", value: "20" },
        ],
      },
      {
        name: "Fuel efficiency summary",
        method: "GET",
        path: "admin/analytics/fuel-summary",
        auth: "admin",
      },
      {
        name: "List subscription plans",
        method: "GET",
        path: "admin/subscriptions/plans",
        auth: "admin",
      },
      {
        name: "Create subscription plan",
        method: "POST",
        path: "admin/subscriptions/plans",
        auth: "admin",
        body: '{\n  "name": "Premium",\n  "priceCents": 999\n}',
      },
      {
        name: "List purchases",
        method: "GET",
        path: "admin/subscriptions/purchases",
        auth: "admin",
      },
      {
        name: "Record purchase",
        method: "POST",
        path: "admin/subscriptions/purchases",
        auth: "admin",
        body: '{\n  "userId": "{{targetUserId}}",\n  "planId": "{{planId}}"\n}',
      },
      {
        name: "List content",
        method: "GET",
        path: "admin/content",
        auth: "admin",
      },
      {
        name: "Upsert content",
        method: "POST",
        path: "admin/content",
        auth: "admin",
        body: '{\n  "section": "privacy_policy",\n  "title": "Privacy Policy",\n  "body": "<p>Content</p>"\n}',
      },
      {
        name: "List feedback",
        method: "GET",
        path: "admin/feedback",
        auth: "admin",
      },
      {
        name: "Update feedback",
        method: "PATCH",
        path: "admin/feedback/{{feedbackId}}",
        auth: "admin",
        body: '{\n  "status": "resolved"\n}',
      },
    ]),
    folder("Public", "", [
      {
        name: "Get content by section",
        method: "GET",
        path: "content/{{contentSection}}",
        auth: "none",
      },
      {
        name: "Submit feedback",
        method: "POST",
        path: "feedback",
        auth: "optional",
        body: '{\n  "message": "Great app!",\n  "rating": 5\n}',
      },
    ]),
  ],
};

const outPath = path.join(process.cwd(), "TankTrack_Postman_Collection.json");
fs.writeFileSync(outPath, JSON.stringify(collection, null, 2), "utf8");

let count = 0;
for (const f of collection.item) {
  count += (f as { item: unknown[] }).item.length;
}
console.log(
  `Wrote ${outPath} (${collection.item.length} folders, ${count} requests)`,
);
