import {IMedia, Media} from "../models/Media";
import {Response} from "express";
import {bucket} from "./bucket";

/**
 * Creates a new media in the database
 * @param clientId The client id of the uploader
 * @param assetName The name of the asset
 * @param assetEnding The file ending of the asset
 */
export const createMedia = (clientId: number, assetName: string, assetEnding: string | undefined) =>
    Media.create({clientId, assetName, assetEnding: assetEnding || "txt"});

/**
 * Gets a media object from an id
 * @param assetId The id of the asset to search
 */
export const getMediaById = (assetId: string) => Media.findOne({where: {assetId}});

/**
 * Gets a complete media object by the asset id
 * @param assetId The id of the asset to search
 */
export const getMediaObject = (assetId: string) => Media.findOne({where: {assetId}}) as Promise<IMedia>;

/**
 * Pipes the provided asset into an express response
 * @param assetId The id of the asset to pipe
 * @param res The express response controller
 */
export const pipeMedia = (assetId: string, res: Response) => bucket.file(assetId).createReadStream().pipe(res);

/**
 * Deletes the provided asset from the database & bucket
 * @param assetId The id of the asset to delete
 */
export const deleteMedia = async (assetId: string) => {
    await Media.destroy({where: {assetId}});
    await bucket.file(assetId).delete();
}