import { DataSource } from 'typeorm';
import { Account } from '../../../repositories/accounts/entity/account.entity';
import {
  License,
  LicenseOrder,
} from '../../../repositories/licenses/entity/license.entity';

export const createAccount = async (
  datasource: DataSource,
  parentAccountId: number,
  tier: number,
  companyName: string,
): Promise<{ accountId: number }> => {
  const { identifiers } = await datasource.getRepository(Account).insert({
    parent_account_id: parentAccountId,
    tier: tier,
    country: 'JP',
    delegation_permission: false,
    locked: false,
    company_name: companyName,
    verified: true,
    deleted_at: '',
    created_by: 'test_runner',
    created_at: new Date(),
    updated_by: 'updater',
    updated_at: new Date(),
  });
  const account = identifiers.pop() as Account;
  return { accountId: account.id };
};

export const createLicense = async (
  datasource: DataSource,
  accountId: number,
): Promise<void> => {
  const { identifiers } = await datasource.getRepository(License).insert({
    expiry_date: null,
    account_id: accountId,
    type: 'NORMAL',
    status: 'Unallocated',
    allocated_user_id: null,
    order_id: null,
    deleted_at: null,
    delete_order_id: null,
    created_by: 'test_runner',
    created_at: new Date(),
    updated_by: 'updater',
    updated_at: new Date(),
  });
  identifiers.pop() as License;
};

export const createLicenseOrder = async (
  datasource: DataSource,
  fromAccountId: number,
  toAccountId: number,
  quantity: number,
  po_number = 'TEST123',
  ordered_at = new Date(),
): Promise<void> => {
  const { identifiers } = await datasource.getRepository(LicenseOrder).insert({
    po_number: po_number,
    from_account_id: fromAccountId,
    to_account_id: toAccountId,
    ordered_at: ordered_at,
    issued_at: null,
    quantity: quantity,
    status: 'Issue Requesting',
    canceled_at: null,
    created_by: 'test_runner',
    created_at: new Date(),
    updated_by: 'updater',
    updated_at: new Date(),
  });
  identifiers.pop() as License;
};
