import * as plugins from './plugins.js';
import { AcmeCertDoc } from './db/index.js';

/**
 * ICertManager implementation backed by smartdata document classes.
 * Persists SmartAcme certificates via AcmeCertDoc so they
 * survive process restarts without re-hitting ACME.
 */
export class StorageBackedCertManager implements plugins.smartacme.ICertManager {
  constructor() {}

  async init(): Promise<void> {}

  async retrieveCertificate(domainName: string): Promise<plugins.smartacme.Cert | null> {
    const doc = await AcmeCertDoc.findByDomain(domainName);
    if (!doc) return null;
    return new plugins.smartacme.Cert({
      id: doc.id,
      domainName: doc.domainName,
      created: doc.created,
      privateKey: doc.privateKey,
      publicKey: doc.publicKey,
      csr: doc.csr,
      validUntil: doc.validUntil,
    });
  }

  async storeCertificate(cert: plugins.smartacme.Cert): Promise<void> {
    let doc = await AcmeCertDoc.findByDomain(cert.domainName);
    if (!doc) {
      doc = new AcmeCertDoc();
      doc.id = cert.id;
      doc.domainName = cert.domainName;
    }
    doc.created = cert.created;
    doc.privateKey = cert.privateKey;
    doc.publicKey = cert.publicKey;
    doc.csr = cert.csr;
    doc.validUntil = cert.validUntil;
    await doc.save();
  }

  async deleteCertificate(domainName: string): Promise<void> {
    const doc = await AcmeCertDoc.findByDomain(domainName);
    if (doc) {
      await doc.delete();
    }
  }

  async close(): Promise<void> {}

  async wipe(): Promise<void> {
    const docs = await AcmeCertDoc.findAll();
    for (const doc of docs) {
      await doc.delete();
    }
  }
}
