/**
 * Plaintext backend driver — stores Secret.data directly in the DB column.
 *
 * This is the bootstrap/default backend. It always exists (seeded on startup)
 * so the system can hold its own backends' auth credentials (e.g. OpenBao
 * token) somewhere before the real backend is configured.
 *
 * The driver is deliberately almost a no-op: the service writes to and reads
 * from `Secret.data` directly. We still route through the driver interface so
 * the service layer can stay uniform.
 */
import type { SecretBackendDriver, SecretData, ExternalRef } from './types.js';

export interface PlaintextDriverDeps {
  /** Queries `prisma.secret.findMany(...)` for the `list` method (migration path). */
  listAllPlaintext: () => Promise<Array<{ name: string; data: SecretData }>>;
}

export class PlaintextDriver implements SecretBackendDriver {
  readonly kind = 'plaintext';

  constructor(private readonly deps: PlaintextDriverDeps) {}

  async read(input: { name: string; externalRef: ExternalRef; data: SecretData }): Promise<SecretData> {
    return input.data;
  }

  async write(input: { name: string; data: SecretData }): Promise<{ externalRef: ExternalRef; storedData: SecretData }> {
    return { externalRef: '', storedData: input.data };
  }

  async delete(_input: { name: string; externalRef: ExternalRef }): Promise<void> {
    // The row deletion itself is the secret service's job; nothing remote to clean up here.
  }

  async list(): Promise<Array<{ name: string; externalRef: ExternalRef }>> {
    const rows = await this.deps.listAllPlaintext();
    return rows.map((r) => ({ name: r.name, externalRef: '' }));
  }

  async healthCheck(): Promise<{ ok: boolean; detail?: string }> {
    return { ok: true, detail: 'plaintext backend (DB)' };
  }
}
