import * as plugins from '../../plugins.ts';
import { CacheDb } from '../classes.cachedb.ts';
import { CachedDocument, TTL } from '../classes.cached.document.ts';
import type { ISecret } from '../../../ts_interfaces/data/secret.ts';

/**
 * Cached secret data from git providers. TTL: 24 hours.
 */
@plugins.smartdata.Collection(() => CacheDb.getInstance().getDb())
export class CachedSecret extends CachedDocument<CachedSecret> {
  @plugins.smartdata.unI()
  public id: string = '';

  @plugins.smartdata.svDb()
  public connectionId: string = '';

  @plugins.smartdata.svDb()
  public scope: 'project' | 'group' = 'project';

  @plugins.smartdata.svDb()
  public scopeId: string = '';

  @plugins.smartdata.svDb()
  public scopeName: string = '';

  @plugins.smartdata.svDb()
  public key: string = '';

  @plugins.smartdata.svDb()
  public value: string = '';

  @plugins.smartdata.svDb()
  public protected: boolean = false;

  @plugins.smartdata.svDb()
  public masked: boolean = false;

  @plugins.smartdata.svDb()
  public environment: string = '';

  constructor() {
    super();
    this.setTTL(TTL.HOURS_24);
  }

  /** Build the composite unique ID */
  static buildId(connectionId: string, scope: string, scopeId: string, key: string): string {
    return `${connectionId}:${scope}:${scopeId}:${key}`;
  }

  /** Create a CachedSecret from an ISecret */
  static fromISecret(secret: ISecret): CachedSecret {
    const doc = new CachedSecret();
    doc.id = CachedSecret.buildId(secret.connectionId, secret.scope, secret.scopeId, secret.key);
    doc.connectionId = secret.connectionId;
    doc.scope = secret.scope;
    doc.scopeId = secret.scopeId;
    doc.scopeName = secret.scopeName;
    doc.key = secret.key;
    doc.value = secret.value;
    doc.protected = secret.protected;
    doc.masked = secret.masked;
    doc.environment = secret.environment;
    return doc;
  }

  /** Convert back to ISecret */
  toISecret(): ISecret {
    return {
      connectionId: this.connectionId,
      scope: this.scope,
      scopeId: this.scopeId,
      scopeName: this.scopeName,
      key: this.key,
      value: this.value,
      protected: this.protected,
      masked: this.masked,
      environment: this.environment,
    };
  }
}
