/*
 * Copyright (C) 2019 StApps
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
import {SCConfigFile, SCSearchQuery, SCSearchResponse, SCThings, SCUuid} from '@openstapps/core';
import {MailQueue} from '../notification/mail-queue.js';
import {Bulk} from './bulk-storage.js';

/**
 * Creates an instance of a database
 */
export type DatabaseConstructor = new (config: SCConfigFile, mailQueue?: MailQueue) => Database;

/**
 * Defines what one database class needs to have defined
 */
export interface Database {
  /**
   * Gets called if a bulk was created
   *
   * The database should
   * @param bulk A bulk to be created
   */
  bulkCreated(bulk: Bulk): Promise<void>;

  /**
   * Gets called if a bulk expires
   *
   * The database should delete all data that is associtated with this bulk
   * @param bulk A bulk which data needs to be removed
   */
  bulkExpired(bulk: Bulk): Promise<void>;

  /**
   * Gets called if a bulk was updated
   *
   * If the database holds a bulk with the same type and source as the given
   * bulk it should be replaced by the given one
   * @param bulk A new bulk whose data should be saved instead of the data of the old bulk
   */
  bulkUpdated(bulk: Bulk): Promise<void>;

  /**
   * Get a single document
   * @param uid Unique identifier of the document
   */
  get(uid: SCUuid): Promise<SCThings>;

  /**
   * Initialize the database (call and wait for all needed methods)
   */
  init(): Promise<void>;

  /**
   * Add a thing to an existing bulk
   * @param thing A StAppsCore thing to be added
   * @param bulk A bulk to which the thing should be added
   */
  post(thing: SCThings, bulk: Bulk): Promise<void>;

  /**
   * Replace an existing thing in any Bulk
   *
   * Currently it is not possible to put an non-existing object
   * @param thing A StAppsCore thing to be added to a bulk
   */
  put(thing: SCThings): Promise<void>;

  /**
   * Search for things
   * @param params Parameters which form a search query to search the backend data
   */
  search(parameters: SCSearchQuery): Promise<SCSearchResponse>;
}
