import { EntityManager, getConnection, MigrationInterface, QueryRunner } from 'typeorm'

export class InsertNewProductDetailStock1687415141200 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<any> {
    await getConnection().transaction(async (trx: EntityManager) => {
      await trx.query(`
        CREATE OR REPLACE FUNCTION insert_new_product_detail_stock()
        RETURNS TRIGGER AS $$
        BEGIN
            INSERT INTO product_detail_stocks (product_detail_id, qty, locked_qty, unassigned_qty, uom_value, locked_uom_value, unassigned_uom_value, updated_at, domain_id)
            VALUES (NEW.id, 0, 0, 0, 0, 0 ,0, NOW(), NEW.domain_id);
            RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;
    `)

      await trx.query(`
        CREATE TRIGGER product_details_trigger
        AFTER INSERT ON product_details
        FOR EACH ROW
        EXECUTE FUNCTION insert_new_product_detail_stock();
    `)
    })
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query('DROP TRIGGER product_details_trigger ON product_details')
    await queryRunner.query('DROP FUNCTION IF EXISTS insert_new_product_detail_stock()')
  }
}
