/// Device management — reads/writes .relicario/devices.json

import type { GitHost } from './git-host';
import type { Device } from '../shared/types';

const DEVICES_PATH = '.relicario/devices.json';

interface DevicesFile {
  devices: Device[];
}

export async function readDevices(gitHost: GitHost): Promise<Device[]> {
  try {
    const raw = await gitHost.readFile(DEVICES_PATH);
    const text = new TextDecoder().decode(raw);
    const parsed: DevicesFile = JSON.parse(text);
    return parsed.devices ?? [];
  } catch {
    return [];
  }
}

export async function writeDevices(
  gitHost: GitHost,
  devices: Device[],
  message: string,
): Promise<void> {
  const content: DevicesFile = { devices };
  const bytes = new TextEncoder().encode(JSON.stringify(content, null, 2));
  await gitHost.writeFile(DEVICES_PATH, bytes, message);
}

export async function addDevice(
  gitHost: GitHost,
  device: Device,
): Promise<void> {
  const existing = await readDevices(gitHost);
  if (existing.some((d) => d.name === device.name)) {
    throw new Error(`device '${device.name}' already exists`);
  }
  existing.push(device);
  await writeDevices(gitHost, existing, `device: add ${device.name}`);
}

export async function revokeDevice(
  gitHost: GitHost,
  name: string,
): Promise<void> {
  const existing = await readDevices(gitHost);
  const filtered = existing.filter((d) => d.name !== name);
  if (filtered.length === existing.length) {
    throw new Error(`device '${name}' not found`);
  }
  await writeDevices(gitHost, filtered, `device: revoke ${name}`);
}
