Skip to content

Colota - Android GPS Location tracker

34.5 KB
Raw Blame
import React from "react"
import { render, fireEvent, waitFor } from "@testing-library/react-native"
import { DEFAULT_AUTH_CONFIG, TRACKING_PRESETS } from "../../types/global"

// --- Mocks ---

const mockSetSettings = jest.fn().mockResolvedValue(undefined)
const mockRestartTracking = jest.fn().mockResolvedValue(true)
const mockSaveSetting = jest.fn().mockResolvedValue(undefined)
const mockGetAuthConfig = jest.fn().mockResolvedValue({ ...DEFAULT_AUTH_CONFIG })
const mockSaveAuthConfig = jest.fn().mockResolvedValue(true)
const mockCreateGeofence = jest.fn().mockResolvedValue(1)
const mockGetGeofences = jest.fn().mockResolvedValue([])
const mockDeleteGeofence = jest.fn().mockResolvedValue(true)
const mockCreateProfile = jest.fn().mockResolvedValue(1)
const mockGetProfiles = jest.fn().mockResolvedValue([])
const mockDeleteProfile = jest.fn().mockResolvedValue(true)
const mockNavigate = jest.fn()
const mockShowAlert = jest.fn()
let mockCurrentEndpoint = ""
let mockUnitSystem = "metric"

jest.mock("../../services/NativeLocationService", () => ({
  __esModule: true,
  default: {
    getAuthConfig: (...args: any[]) => mockGetAuthConfig(...args),
    saveAuthConfig: (...args: any[]) => mockSaveAuthConfig(...args),
    saveSetting: (...args: any[]) => mockSaveSetting(...args),
    createGeofence: (...args: any[]) => mockCreateGeofence(...args),
    getGeofences: (...args: any[]) => mockGetGeofences(...args),
    deleteGeofence: (...args: any[]) => mockDeleteGeofence(...args),
    createProfile: (...args: any[]) => mockCreateProfile(...args),
    getProfiles: (...args: any[]) => mockGetProfiles(...args),
    deleteProfile: (...args: any[]) => mockDeleteProfile(...args),
    getSetting: (key: string) => Promise.resolve(key === "unitSystem" ? mockUnitSystem : "")
  }
}))

jest.mock("../../services/modalService", () => ({
  showAlert: (...args: any[]) => mockShowAlert(...args)
}))

jest.mock("../../contexts/TrackingProvider", () => ({
  useTracking: () => ({
    settings: { ...require("../../types/global").DEFAULT_SETTINGS, endpoint: mockCurrentEndpoint },
    setSettings: mockSetSettings,
    restartTracking: mockRestartTracking
  })
}))

jest.mock("../../hooks/useTheme", () => ({
  useTheme: () => ({
    colors: {
      primary: "#0d9488",
      primaryDark: "#115E59",
      border: "#e5e7eb",
      text: "#000",
      textSecondary: "#6b7280",
      textLight: "#9ca3af",
      background: "#fff",
      info: "#3b82f6",
      success: "#22c55e",
      error: "#ef4444",
      card: "#fff",
      textOnPrimary: "#fff",
      textDisabled: "#d1d5db"
    }
  })
}))

jest.mock("../../components", () => {
  const R = require("react")
  const { View, Text, Pressable } = require("react-native")
  return {
    Toggle: function (props: any) {
      return require("react").createElement(require("react-native").Switch, {
        testID: props.testID,
        value: props.value,
        onValueChange: props.onValueChange,
        disabled: props.disabled,
        accessibilityLabel: props.accessibilityLabel
      })
    },
    Container: ({ children }: any) => R.createElement(View, null, children),
    Card: ({ children }: any) => R.createElement(View, null, children),
    SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
    Divider: () => R.createElement(View, null),
    StatRow: ({ label, value }: any) =>
      R.createElement(View, null, R.createElement(Text, null, label), R.createElement(Text, null, value)),
    FieldMessage: ({ children }: any) => R.createElement(Text, null, children),
    EmptyState: ({ title, hint }: any) =>
      R.createElement(View, null, R.createElement(Text, null, title), hint ? R.createElement(Text, null, hint) : null),
    SettingRow: ({ label, hint, children }: any) =>
      R.createElement(
        View,
        null,
        R.createElement(Text, null, label),
        hint ? R.createElement(Text, null, hint) : null,
        children
      ),
    Button: ({ title, onPress, disabled }: any) =>
      R.createElement(Pressable, { onPress, disabled, accessibilityRole: "button" }, R.createElement(Text, null, title))
  }
})

jest.mock("../../utils/logger", () => ({
  logger: { debug: jest.fn(), error: jest.fn(), warn: jest.fn(), info: jest.fn() }
}))

import { SetupImportScreen } from "../SetupImportScreen"
import { loadDisplayPreferences } from "../../utils/geo"

// --- Helpers ---

function encode(obj: object): string {
  return btoa(JSON.stringify(obj))
}

function renderScreen(configParam?: string) {
  return render(
    <SetupImportScreen
      route={{ params: configParam !== undefined ? { config: configParam } : {} }}
      navigation={{ navigate: mockNavigate }}
    />
  )
}

// --- Tests ---

beforeEach(async () => {
  jest.clearAllMocks()
  mockCurrentEndpoint = ""
  mockUnitSystem = "metric"
  await loadDisplayPreferences()
})

describe("SetupImportScreen", () => {
  describe("parsing and validation", () => {
    it("shows error when no config param is provided", () => {
      const { getByText } = renderScreen()
      expect(getByText("Invalid configuration")).toBeTruthy()
      expect(getByText("No configuration data in URL")).toBeTruthy()
    })

    it("shows error for invalid base64", () => {
      const { getByText } = renderScreen("!!!not-base64!!!")
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("shows error for valid base64 but invalid JSON", () => {
      const { getByText } = renderScreen(btoa("not json"))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("shows error when config has no valid settings", () => {
      const { getByText } = renderScreen(encode({ unknownKey: "value" }))
      expect(getByText("Invalid configuration")).toBeTruthy()
      expect(getByText("No valid settings found in configuration")).toBeTruthy()
    })

    it("parses valid endpoint config", () => {
      const { getByText } = renderScreen(encode({ endpoint: "https://my-server.com/api" }))
      expect(getByText("Sends locations to")).toBeTruthy()
      expect(getByText("https://my-server.com/api")).toBeTruthy()
    })

    it("parses tracking settings", () => {
      const { getByText } = renderScreen(encode({ interval: 10, distance: 5, syncInterval: 0 }))
      expect(getByText("10 s")).toBeTruthy()
      expect(getByText("5m")).toBeTruthy()
      expect(getByText("Instant")).toBeTruthy()
    })

    // The user judges the link by these values, so they read as the settings screens print them, not as stored ids.
    it("prints durations, the sync condition and the auth method the way the settings screens do", () => {
      const { getByText } = renderScreen(
        encode({ syncInterval: 300, syncCondition: "wifi_any", auth: { type: "basic", username: "u" } })
      )
      expect(getByText("5 min")).toBeTruthy()
      expect(getByText("Wi-Fi or Ethernet")).toBeTruthy()
      expect(getByText("Basic auth")).toBeTruthy()
    })

    it("prints distances in the unit the user chose", async () => {
      mockUnitSystem = "imperial"
      await loadDisplayPreferences()
      const { getByText } = renderScreen(encode({ distance: 100 }))
      expect(getByText("328 ft")).toBeTruthy()
    })

    it("parses API settings", () => {
      const { getByText } = renderScreen(encode({ apiTemplate: "owntracks", httpMethod: "POST" }))
      expect(getByText("OwnTracks")).toBeTruthy()
      expect(getByText("POST")).toBeTruthy()
    })

    it("parses auth settings with masked token", () => {
      const { getByText, getAllByText } = renderScreen(
        encode({ auth: { type: "bearer", bearerToken: "abcdefghijkl" } })
      )
      // The method's value and the token row's label read the same.
      expect(getAllByText("Bearer token")).toHaveLength(2)
      // Token should be masked: first 4 + dots + last 4
      expect(getByText(/abcd.*ijkl/)).toBeTruthy()
    })

    it("parses custom headers", () => {
      const { getByText } = renderScreen(encode({ customHeaders: { "X-Api-Key": "secret" } }))
      expect(getByText("1 header")).toBeTruthy()
    })

    it("counts a single mapped field in the singular", () => {
      const { getByText } = renderScreen(encode({ fieldMap: { lat: "latitude" } }))
      expect(getByText("1 field")).toBeTruthy()
    })

    it("rejects invalid interval (negative)", () => {
      const { getByText } = renderScreen(encode({ interval: -5 }))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("rejects invalid auth type", () => {
      const { getByText } = renderScreen(encode({ auth: { type: "oauth" } }))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("rejects invalid API template", () => {
      const { getByText } = renderScreen(encode({ apiTemplate: "invalid" }))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("counts settings correctly in subtitle", () => {
      const { getByText } = renderScreen(encode({ endpoint: "https://test.com", interval: 10 }))
      expect(getByText(/2 settings/)).toBeTruthy()
    })

    it("shows singular 'setting' for single entry", () => {
      const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))
      expect(getByText(/apply 1 setting\./)).toBeTruthy()
    })
  })

  // The confirmation is the only thing between a phishing link and the user's location stream.
  describe("endpoint confirmation", () => {
    it("prints the host on its own line, so a lookalike prefix cannot stand in for it", () => {
      const endpoint = "https://my-server.com.evil.example/api/locations"
      const { getByText } = renderScreen(encode({ endpoint }))

      expect(getByText("my-server.com.evil.example")).toBeTruthy()
      expect(getByText(endpoint)).toBeTruthy()
    })

    it("never cuts the address to one line, because the cut would hide where locations go", () => {
      const endpoint = `https://my-server.com.${"a".repeat(80)}.evil.example/api`
      const { getByText } = renderScreen(encode({ endpoint }))

      expect(getByText(endpoint).props.numberOfLines).toBeUndefined()
      expect(getByText(endpoint.slice(8, -4)).props.numberOfLines).toBeUndefined()
    })

    it("refuses an address whose host hides behind user@, which reads as the trusted host", () => {
      const { getByText, queryByText } = renderScreen(
        encode({ endpoint: "https://[email protected]/api", interval: 10 })
      )

      expect(getByText(/must be a plain host/)).toBeTruthy()
      expect(queryByText("Sends locations to")).toBeNull()
    })

    it("says which server the link replaces when one is already configured", () => {
      mockCurrentEndpoint = "https://my-server.com/api"
      const { getByText } = renderScreen(encode({ endpoint: "https://evil.example/api" }))

      expect(getByText("Replaces your current server, my-server.com")).toBeTruthy()
    })

    it("stays quiet on a first setup and on a link that carries the configured address", () => {
      const first = renderScreen(encode({ endpoint: "https://my-server.com/api" }))
      expect(first.queryByText(/Replaces your current server/)).toBeNull()
      first.unmount()

      mockCurrentEndpoint = "https://my-server.com/api"
      const same = renderScreen(encode({ endpoint: "https://my-server.com/api" }))
      expect(same.queryByText(/Replaces your current server/)).toBeNull()
    })

    it("tells the user to apply a link only from a trusted source", () => {
      const { getByText } = renderScreen(encode({ endpoint: "https://my-server.com/api" }))
      expect(getByText(/only if you trust where it came from/)).toBeTruthy()
    })
  })

  describe("apply configuration", () => {
    it("applies settings and navigates to Dashboard", async () => {
      const config = { endpoint: "https://test.com", interval: 15 }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockShowAlert).toHaveBeenCalledWith(
          "Configuration Applied",
          "Settings have been updated successfully.",
          "success"
        )
      })

      expect(mockNavigate).toHaveBeenCalledWith("Dashboard")
      expect(mockSetSettings).toHaveBeenCalledWith(
        expect.objectContaining({ endpoint: "https://test.com", interval: 15, hasCompletedSetup: true })
      )
    })

    it("applies auth config when provided", async () => {
      const config = { endpoint: "https://test.com", auth: { type: "bearer", bearerToken: "mytoken" } }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockSaveAuthConfig).toHaveBeenCalledWith(
          expect.objectContaining({ authType: "bearer", bearerToken: "mytoken" })
        )
      })
    })

    it("marks hasCompletedSetup as true", async () => {
      const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockSetSettings).toHaveBeenCalledWith(expect.objectContaining({ hasCompletedSetup: true }))
      })
    })

    it("sets syncPreset to 'custom' when values don't match a preset", async () => {
      const config = { interval: 15, distance: 3, syncInterval: 120 }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockSetSettings).toHaveBeenCalledWith(expect.objectContaining({ syncPreset: "custom" }))
      })
    })

    it("sets syncPreset to matching preset when values match", async () => {
      const balanced = TRACKING_PRESETS.balanced
      const config = {
        interval: balanced.interval,
        distance: balanced.distance,
        syncInterval: balanced.syncInterval,
        retryInterval: balanced.retryInterval
      }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockSetSettings).toHaveBeenCalledWith(expect.objectContaining({ syncPreset: "balanced" }))
      })
    })

    it("restarts tracking after the auth write, because a running service reads its credentials only at start", async () => {
      const config = { endpoint: "https://test.com", auth: { type: "bearer", bearerToken: "mytoken" } }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => expect(mockRestartTracking).toHaveBeenCalledTimes(1))
      expect(mockRestartTracking).toHaveBeenCalledWith(expect.objectContaining({ endpoint: "https://test.com" }))
      expect(mockRestartTracking.mock.invocationCallOrder[0]).toBeGreaterThan(
        mockSaveAuthConfig.mock.invocationCallOrder[0]
      )
    })

    it("shows error alert on failure", async () => {
      mockSetSettings.mockRejectedValueOnce(new Error("fail"))
      const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to apply configuration. Please try again.", "error")
      })
      expect(mockRestartTracking).not.toHaveBeenCalled()
    })
  })

  describe("cancel", () => {
    it("navigates to Dashboard on cancel", () => {
      const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))
      fireEvent.press(getByText("Cancel"))
      expect(mockNavigate).toHaveBeenCalledWith("Dashboard")
    })

    it("navigates to Dashboard on Go Back (error state)", () => {
      const { getByText } = renderScreen()
      fireEvent.press(getByText("Go back"))
      expect(mockNavigate).toHaveBeenCalledWith("Dashboard")
    })
  })

  describe("geofences", () => {
    const validGeofence = { name: "Home", lat: 52.5, lon: 13.4, radius: 100 }

    it("parses a valid geofence and shows it under Geofences", () => {
      const { getByText } = renderScreen(encode({ geofences: [validGeofence] }))
      expect(getByText("Geofences")).toBeTruthy()
      expect(getByText("Home")).toBeTruthy()
      expect(getByText("100m")).toBeTruthy()
    })

    it("never shows a zone named Endpoint as the server, because the name is the link writer's text", () => {
      const { getByText, queryByText } = renderScreen(encode({ geofences: [{ ...validGeofence, name: "Endpoint" }] }))
      expect(queryByText("Sends locations to")).toBeNull()
      expect(getByText("Endpoint")).toBeTruthy()
      expect(getByText("100m")).toBeTruthy()
    })

    it("rejects a geofence missing required fields", () => {
      const { getByText } = renderScreen(encode({ geofences: [{ name: "X", lat: 52.5 }] }))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("rejects a geofence with non-positive radius", () => {
      const { getByText } = renderScreen(encode({ geofences: [{ ...validGeofence, radius: 0 }] }))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("skips invalid entries but keeps valid ones", () => {
      const config = {
        geofences: [{ name: "X", lat: 52.5 }, validGeofence]
      }
      const { getByText, queryByText } = renderScreen(encode(config))
      expect(getByText("Home")).toBeTruthy()
      expect(queryByText("X")).toBeNull()
    })

    it("calls createGeofence on apply with defaults filled in", async () => {
      const { getByText } = renderScreen(encode({ geofences: [validGeofence] }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
      })
      expect(mockCreateGeofence).toHaveBeenCalledWith({
        name: "Home",
        lat: 52.5,
        lon: 13.4,
        radius: 100,
        enabled: true,
        pauseTracking: false,
        pauseOnWifi: false,
        pauseOnMotionless: false,
        motionlessTimeoutMinutes: 10,
        heartbeatEnabled: false,
        heartbeatIntervalMinutes: 15
      })
    })

    it("preserves explicit boolean and numeric flags", async () => {
      const config = {
        geofences: [
          {
            ...validGeofence,
            pauseTracking: true,
            pauseOnWifi: true,
            pauseOnMotionless: true,
            motionlessTimeoutMinutes: 5,
            heartbeatEnabled: true,
            heartbeatIntervalMinutes: 30,
            enabled: false
          }
        ]
      }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
      })
      expect(mockCreateGeofence).toHaveBeenCalledWith(
        expect.objectContaining({
          pauseTracking: true,
          pauseOnWifi: true,
          pauseOnMotionless: true,
          motionlessTimeoutMinutes: 5,
          heartbeatEnabled: true,
          heartbeatIntervalMinutes: 30,
          enabled: false
        })
      )
    })

    it("creates multiple geofences in order", async () => {
      const config = {
        geofences: [
          { name: "Home", lat: 52.5, lon: 13.4, radius: 100 },
          { name: "Office", lat: 52.6, lon: 13.5, radius: 200 }
        ]
      }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateGeofence).toHaveBeenCalledTimes(2)
      })
      expect(mockCreateGeofence.mock.calls[0][0].name).toBe("Home")
      expect(mockCreateGeofence.mock.calls[1][0].name).toBe("Office")
    })

    it("tells the geofence screens to reload once the zones are written, as the editor does", async () => {
      const { DeviceEventEmitter } = require("react-native")
      const emit = jest.spyOn(DeviceEventEmitter, "emit")
      const { getByText } = renderScreen(encode({ geofences: [validGeofence] }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => expect(mockCreateGeofence).toHaveBeenCalledTimes(1))
      expect(emit).toHaveBeenCalledWith("geofenceUpdated")
      emit.mockRestore()
    })

    it("does not call createGeofence when no geofences in config", async () => {
      const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockShowAlert).toHaveBeenCalledWith("Configuration Applied", expect.any(String), "success")
      })
      expect(mockCreateGeofence).not.toHaveBeenCalled()
    })
  })

  describe("replace geofences toggle", () => {
    const validGeofence = { name: "Home", lat: 52.5, lon: 13.4, radius: 100 }

    beforeEach(() => {
      mockGetGeofences.mockReset()
      mockGetGeofences.mockResolvedValue([])
      mockDeleteGeofence.mockReset()
      mockDeleteGeofence.mockResolvedValue(true)
    })

    it("hides the toggle when no geofences are in the import", () => {
      const { queryByTestId } = renderScreen(encode({ endpoint: "https://test.com" }))
      expect(queryByTestId("replace-imports-switch")).toBeNull()
    })

    it("shows the toggle when geofences are in the import", () => {
      const { getByTestId } = renderScreen(encode({ geofences: [validGeofence] }))
      expect(getByTestId("replace-imports-switch")).toBeTruthy()
    })

    it("does not delete existing zones when toggle is off (default)", async () => {
      mockGetGeofences.mockResolvedValueOnce([{ id: 7, name: "Home", lat: 0, lon: 0, radius: 50, enabled: true }])
      const { getByText } = renderScreen(encode({ geofences: [validGeofence] }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
      })
      expect(mockGetGeofences).not.toHaveBeenCalled()
      expect(mockDeleteGeofence).not.toHaveBeenCalled()
    })

    it("deletes matching zones before creating when toggle is on", async () => {
      mockGetGeofences.mockResolvedValueOnce([
        { id: 7, name: "Home", lat: 0, lon: 0, radius: 50, enabled: true },
        { id: 8, name: "Other", lat: 0, lon: 0, radius: 50, enabled: true }
      ])
      const { getByText, getByTestId } = renderScreen(encode({ geofences: [validGeofence] }))

      fireEvent(getByTestId("replace-imports-switch"), "valueChange", true)
      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
      })
      expect(mockDeleteGeofence).toHaveBeenCalledTimes(1)
      expect(mockDeleteGeofence).toHaveBeenCalledWith(7)
    })

    it("creates without delete when toggle is on but no name match exists", async () => {
      mockGetGeofences.mockResolvedValueOnce([{ id: 8, name: "Other", lat: 0, lon: 0, radius: 50, enabled: true }])
      const { getByText, getByTestId } = renderScreen(encode({ geofences: [validGeofence] }))

      fireEvent(getByTestId("replace-imports-switch"), "valueChange", true)
      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
      })
      expect(mockDeleteGeofence).not.toHaveBeenCalled()
    })

    it("only fetches existing zones once when replacing multiple imports", async () => {
      mockGetGeofences.mockResolvedValueOnce([
        { id: 7, name: "Home", lat: 0, lon: 0, radius: 50, enabled: true },
        { id: 8, name: "Office", lat: 0, lon: 0, radius: 50, enabled: true }
      ])
      const config = {
        geofences: [
          { name: "Home", lat: 52.5, lon: 13.4, radius: 100 },
          { name: "Office", lat: 52.6, lon: 13.5, radius: 200 }
        ]
      }
      const { getByText, getByTestId } = renderScreen(encode(config))

      fireEvent(getByTestId("replace-imports-switch"), "valueChange", true)
      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateGeofence).toHaveBeenCalledTimes(2)
      })
      expect(mockGetGeofences).toHaveBeenCalledTimes(1)
      expect(mockDeleteGeofence).toHaveBeenCalledTimes(2)
    })
  })

  describe("profiles", () => {
    const validProfile = {
      name: "Driving",
      interval: 3,
      distance: 5,
      syncInterval: 60,
      priority: 20,
      activationDelay: 5,
      deactivationDelay: 30,
      enabled: true,
      condition: { type: "speed_above", speedThreshold: 8.33 }
    }

    beforeEach(() => {
      mockGetProfiles.mockReset()
      mockGetProfiles.mockResolvedValue([])
      mockDeleteProfile.mockReset()
      mockDeleteProfile.mockResolvedValue(true)
      mockCreateProfile.mockReset()
      mockCreateProfile.mockResolvedValue(1)
    })

    it("parses a valid profile and shows it under Tracking profiles", () => {
      const { getByText } = renderScreen(encode({ profiles: [validProfile] }))
      expect(getByText("Tracking profiles")).toBeTruthy()
      expect(getByText("Driving")).toBeTruthy()
    })

    it("rejects a profile missing name", () => {
      const { getByText } = renderScreen(encode({ profiles: [{ ...validProfile, name: "" }] }))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("rejects a profile with unknown condition type", () => {
      const config = { profiles: [{ ...validProfile, condition: { type: "bogus" } }] }
      const { getByText } = renderScreen(encode(config))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("rejects a speed profile missing speedThreshold", () => {
      const config = { profiles: [{ ...validProfile, condition: { type: "speed_above" } }] }
      const { getByText } = renderScreen(encode(config))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("rejects a named-network profile without a network name", () => {
      const config = { profiles: [{ ...validProfile, condition: { type: "wifi_ssid" } }] }
      const { getByText } = renderScreen(encode(config))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("imports a named-network profile with its SSID, trimmed", async () => {
      const config = {
        profiles: [{ ...validProfile, condition: { type: "wifi_ssid", ssid: "  HomeNet  " } }]
      }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => expect(mockCreateProfile).toHaveBeenCalledTimes(1))
      expect(mockCreateProfile).toHaveBeenCalledWith(
        expect.objectContaining({ condition: { type: "wifi_ssid", ssid: "HomeNet" } })
      )
    })

    it("rejects a Bluetooth profile without a valid device address", () => {
      for (const condition of [
        { type: "bluetooth_device" },
        { type: "bluetooth_device", bluetoothAddress: "My Car" }
      ]) {
        const { getByText, unmount } = renderScreen(encode({ profiles: [{ ...validProfile, condition }] }))
        expect(getByText("Invalid configuration")).toBeTruthy()
        unmount()
      }
    })

    it("imports a Bluetooth profile with its address uppercased and its name trimmed", async () => {
      const config = {
        profiles: [
          {
            ...validProfile,
            condition: { type: "bluetooth_device", bluetoothAddress: " aa:bb:cc:dd:ee:ff ", bluetoothName: " My Car " }
          }
        ]
      }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => expect(mockCreateProfile).toHaveBeenCalledTimes(1))
      expect(mockCreateProfile).toHaveBeenCalledWith(
        expect.objectContaining({
          condition: { type: "bluetooth_device", bluetoothAddress: "AA:BB:CC:DD:EE:FF", bluetoothName: "My Car" }
        })
      )
    })

    it("accepts the any-network condition without extra fields", () => {
      const config = { profiles: [{ ...validProfile, condition: { type: "wifi_any" } }] }
      const { getByText } = renderScreen(encode(config))
      expect(getByText("Driving")).toBeTruthy()
    })

    it("accepts a non-speed condition without speedThreshold", () => {
      const config = {
        profiles: [{ ...validProfile, condition: { type: "charging" } }]
      }
      const { getByText } = renderScreen(encode(config))
      expect(getByText("Driving")).toBeTruthy()
    })

    it("rejects a profile with interval < 1", () => {
      const { getByText } = renderScreen(encode({ profiles: [{ ...validProfile, interval: 0 }] }))
      expect(getByText("Invalid configuration")).toBeTruthy()
    })

    it("calls createProfile on apply with all fields", async () => {
      const { getByText } = renderScreen(encode({ profiles: [validProfile] }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateProfile).toHaveBeenCalledTimes(1)
      })
      expect(mockCreateProfile).toHaveBeenCalledWith({
        name: "Driving",
        interval: 3,
        distance: 5,
        syncInterval: 60,
        priority: 20,
        activationDelay: 5,
        deactivationDelay: 30,
        enabled: true,
        condition: { type: "speed_above", speedThreshold: 8.33 }
      })
    })

    it("fills in default priority/delay/enabled when omitted", async () => {
      const minimal = {
        name: "Charging",
        interval: 10,
        distance: 0,
        syncInterval: 0,
        condition: { type: "charging" }
      }
      const { getByText } = renderScreen(encode({ profiles: [minimal] }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateProfile).toHaveBeenCalledTimes(1)
      })
      expect(mockCreateProfile).toHaveBeenCalledWith(
        expect.objectContaining({
          name: "Charging",
          priority: 10,
          activationDelay: 0,
          deactivationDelay: 60,
          enabled: true,
          condition: { type: "charging" }
        })
      )
    })

    it("preserves stationary profile interval as set, even when large", async () => {
      const config = {
        profiles: [
          {
            name: "Stationary",
            interval: 3600,
            distance: 0,
            syncInterval: 0,
            condition: { type: "stationary" }
          }
        ]
      }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateProfile).toHaveBeenCalledTimes(1)
      })
      expect(mockCreateProfile.mock.calls[0][0].interval).toBe(3600)
    })

    it("leaves non-stationary profile intervals untouched", async () => {
      const config = {
        profiles: [
          {
            name: "Driving",
            interval: 3600,
            distance: 0,
            syncInterval: 0,
            condition: { type: "speed_above", speedThreshold: 8.33 }
          }
        ]
      }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateProfile).toHaveBeenCalledTimes(1)
      })
      expect(mockCreateProfile.mock.calls[0][0].interval).toBe(3600)
    })

    it("creates multiple profiles in order", async () => {
      const config = {
        profiles: [validProfile, { ...validProfile, name: "Stationary", condition: { type: "stationary" } }]
      }
      const { getByText } = renderScreen(encode(config))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateProfile).toHaveBeenCalledTimes(2)
      })
      expect(mockCreateProfile.mock.calls[0][0].name).toBe("Driving")
      expect(mockCreateProfile.mock.calls[1][0].name).toBe("Stationary")
    })

    it("does not call createProfile when no profiles in config", async () => {
      const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockShowAlert).toHaveBeenCalledWith("Configuration Applied", expect.any(String), "success")
      })
      expect(mockCreateProfile).not.toHaveBeenCalled()
    })

    it("deletes matching profiles before creating when replace toggle is on", async () => {
      mockGetProfiles.mockResolvedValueOnce([
        {
          id: 5,
          name: "Driving",
          interval: 1,
          distance: 0,
          syncInterval: 0,
          priority: 0,
          deactivationDelay: 0,
          enabled: true,
          condition: { type: "charging" }
        },
        {
          id: 6,
          name: "Other",
          interval: 1,
          distance: 0,
          syncInterval: 0,
          priority: 0,
          deactivationDelay: 0,
          enabled: true,
          condition: { type: "charging" }
        }
      ])
      const { getByText, getByTestId } = renderScreen(encode({ profiles: [validProfile] }))

      fireEvent(getByTestId("replace-imports-switch"), "valueChange", true)
      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateProfile).toHaveBeenCalledTimes(1)
      })
      expect(mockDeleteProfile).toHaveBeenCalledTimes(1)
      expect(mockDeleteProfile).toHaveBeenCalledWith(5)
    })

    it("defaults to appending without deleting when replace toggle is off", async () => {
      mockGetProfiles.mockResolvedValueOnce([
        {
          id: 5,
          name: "Driving",
          interval: 1,
          distance: 0,
          syncInterval: 0,
          priority: 0,
          deactivationDelay: 0,
          enabled: true,
          condition: { type: "charging" }
        }
      ])
      const { getByText } = renderScreen(encode({ profiles: [validProfile] }))

      fireEvent.press(getByText("Apply configuration"))

      await waitFor(() => {
        expect(mockCreateProfile).toHaveBeenCalledTimes(1)
      })
      expect(mockGetProfiles).not.toHaveBeenCalled()
      expect(mockDeleteProfile).not.toHaveBeenCalled()
    })
  })

  // A link is written by someone else: once its address fails a check, none of it has earned an Apply button.
  describe("rejected link", () => {
    it("offers no way to apply the rest of a link whose address was rejected", () => {
      const { getByText, queryByText } = renderScreen(encode({ endpoint: "notaurl", interval: 10 }))

      expect(getByText("Invalid configuration")).toBeTruthy()
      expect(getByText(/HTTP not allowed for public hosts\. Nothing from this link will be applied\./)).toBeTruthy()
      expect(queryByText("Apply configuration")).toBeNull()
      expect(queryByText("10s")).toBeNull()
    })

    it("writes nothing when the user leaves a rejected link", () => {
      const { getByText } = renderScreen(encode({ endpoint: "https://[email protected]/api", interval: 10 }))

      fireEvent.press(getByText("Go back"))

      expect(mockSetSettings).not.toHaveBeenCalled()
      expect(mockSaveAuthConfig).not.toHaveBeenCalled()
      expect(mockNavigate).toHaveBeenCalledWith("Dashboard")
    })
  })
})