import { DataSource } from 'typeorm';
import { Workflow } from '../../../repositories/workflows/entity/workflow.entity';
import { WorkflowTypist } from '../../../repositories/workflows/entity/workflow_typists.entity';

// Workflowを作成する
export const createWorkflow = async (
  datasource: DataSource,
  accountId: number,
  authorId: number,
  worktypeId?: number | undefined,
  templateId?: number | undefined,
): Promise<Workflow> => {
  const { identifiers } = await datasource.getRepository(Workflow).insert({
    account_id: accountId,
    author_id: authorId,
    worktype_id: worktypeId ?? undefined,
    template_id: templateId ?? undefined,
    created_by: 'test_runner',
    created_at: new Date(),
    updated_by: 'updater',
    updated_at: new Date(),
  });
  const workflow = identifiers.pop() as Workflow;

  return workflow;
};

// Workflow一覧を取得する
export const getWorkflows = async (
  datasource: DataSource,
  accountId: number,
): Promise<Workflow[]> => {
  return await datasource.getRepository(Workflow).find({
    where: {
      account_id: accountId,
    },
  });
};

// Workflow一覧全体を取得する
export const getAllWorkflows = async (
  datasource: DataSource,
): Promise<Workflow[]> => {
  return await datasource.getRepository(Workflow).find();
};

// Workflowを取得する
export const getWorkflow = async (
  datasource: DataSource,
  accountId: number,
  id: number,
): Promise<Workflow | null> => {
  return await datasource.getRepository(Workflow).findOne({
    where: {
      account_id: accountId,
      id: id,
    },
  });
};

// Workflowを作成する
export const createWorkflowTypist = async (
  datasource: DataSource,
  workflowId: number,
  typistUserId?: number | undefined,
  typistGroupId?: number | undefined,
): Promise<Workflow> => {
  const { identifiers } = await datasource
    .getRepository(WorkflowTypist)
    .insert({
      workflow_id: workflowId,
      typist_id: typistUserId ?? undefined,
      typist_group_id: typistGroupId ?? undefined,
      created_by: 'test_runner',
      created_at: new Date(),
      updated_by: 'updater',
      updated_at: new Date(),
    });
  const workflow = identifiers.pop() as Workflow;

  return workflow;
};

// WorkflowTypist一覧を取得する
export const getWorkflowTypists = async (
  datasource: DataSource,
  workflowId: number,
): Promise<WorkflowTypist[]> => {
  return await datasource.getRepository(WorkflowTypist).find({
    where: {
      workflow_id: workflowId,
    },
  });
};

// WorkflowTypist一覧全件を取得する
export const getAllWorkflowTypists = async (
  datasource: DataSource,
): Promise<WorkflowTypist[]> => {
  return await datasource.getRepository(WorkflowTypist).find();
};
