import { getDb, pgAll, pgGet } from '@/shared/db';
import type { DevicePermissionsRow, PermissionsPayload } from './types';

export const DevicePermissionsRepo = {
  async upsert(deviceId: string, permissions: PermissionsPayload): Promise<DevicePermissionsRow> {
    const db = getDb();
    return pgGet<DevicePermissionsRow>(
      db,
      `INSERT INTO macsync.device_permissions (device_id, permissions, updated_at)
       VALUES ($1, $2, now())
       ON CONFLICT (device_id) DO UPDATE
         SET permissions = EXCLUDED.permissions,
             updated_at  = now()
       RETURNING device_id, permissions, updated_at::text`,
      [deviceId, JSON.stringify(permissions)],
    ) as Promise<DevicePermissionsRow>;
  },

  async listAll(): Promise<DevicePermissionsRow[]> {
    const db = getDb();
    return pgAll<DevicePermissionsRow>(
      db,
      `SELECT device_id, permissions, updated_at::text
       FROM macsync.device_permissions
       ORDER BY updated_at DESC`,
    );
  },
};
