import { DataSource } from 'typeorm';
import { TemplateFile } from '../../../repositories/template_files/entity/template_file.entity';

export const createTemplateFile = async (
  datasource: DataSource,
  accountId: number,
  name: string,
  url: string,
): Promise<TemplateFile> => {
  const { identifiers } = await datasource.getRepository(TemplateFile).insert({
    account_id: accountId,
    file_name: name,
    url: url,
    created_by: 'test_runner',
    created_at: new Date(),
    updated_by: 'updater',
    updated_at: new Date(),
  });

  const template = identifiers.pop() as TemplateFile;
  const templateFile = await datasource.getRepository(TemplateFile).findOne({
    where: {
      id: template.id,
    },
  });
  if (!templateFile) {
    fail();
  }

  return templateFile;
};

export const getTemplateFiles = async (
  datasource: DataSource,
  accountId: number,
): Promise<TemplateFile[]> => {
  const templates = await datasource.getRepository(TemplateFile).find({
    where: {
      account_id: accountId,
    },
  });
  return templates;
};
