import * as plugins from '../../plugins.js';
import { DcRouterDb } from '../classes.dcrouter-db.js';
import type { IApiTokenPolicy, TApiTokenScope } from '../../../ts_interfaces/data/route-management.js';

const getDb = () => DcRouterDb.getInstance().getDb();

@plugins.smartdata.Collection(() => getDb())
export class ApiTokenDoc extends plugins.smartdata.SmartDataDbDoc<ApiTokenDoc, ApiTokenDoc> {
  @plugins.smartdata.unI()
  @plugins.smartdata.svDb()
  public id!: string;

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

  @plugins.smartdata.svDb()
  public tokenHash!: string;

  @plugins.smartdata.svDb()
  public scopes!: TApiTokenScope[];

  @plugins.smartdata.svDb()
  public policy?: IApiTokenPolicy;

  @plugins.smartdata.svDb()
  public createdAt!: number;

  @plugins.smartdata.svDb()
  public expiresAt!: number | null;

  @plugins.smartdata.svDb()
  public lastUsedAt!: number | null;

  @plugins.smartdata.svDb()
  public createdBy!: string;

  @plugins.smartdata.svDb()
  public enabled!: boolean;

  constructor() {
    super();
  }

  public static async findById(id: string): Promise<ApiTokenDoc | null> {
    return await ApiTokenDoc.getInstance({ id });
  }

  public static async findByTokenHash(tokenHash: string): Promise<ApiTokenDoc | null> {
    return await ApiTokenDoc.getInstance({ tokenHash });
  }

  public static async findAll(): Promise<ApiTokenDoc[]> {
    return await ApiTokenDoc.getInstances({});
  }

  public static async findEnabled(): Promise<ApiTokenDoc[]> {
    return await ApiTokenDoc.getInstances({ enabled: true });
  }
}
