'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // Check if column already exists
    const tableDescription = await queryInterface.describeTable('builds');
    if (tableDescription.type) {
      console.log('Column "type" already exists in builds table, skipping migration');
      return;
    }

    // Create ENUM type first (PostgreSQL specific)
    // Use DO block to handle case where type already exists
    await queryInterface.sequelize.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'enum_builds_type') THEN
          CREATE TYPE "enum_builds_type" AS ENUM ('automation', 'manual');
        END IF;
      END
      $$;
    `);

    // Add the column with the enum type
    await queryInterface.sequelize.query(`
      ALTER TABLE "builds"
      ADD COLUMN "type" "enum_builds_type" NOT NULL DEFAULT 'automation';
    `);

    // Add comment to the column
    await queryInterface.sequelize.query(`
      COMMENT ON COLUMN "builds"."type" IS 'Type of build: automation (from test frameworks) or manual (from manual device sessions)';
    `);

    // Add index for efficient filtering by type
    const indexes = await queryInterface.showIndex('builds');
    const indexExists = indexes.some(idx => idx.name === 'builds_type_idx');
    if (!indexExists) {
      await queryInterface.addIndex('builds', ['type'], {
        name: 'builds_type_idx',
      });
    }
  },

  async down(queryInterface, Sequelize) {
    // Remove index first
    try {
      await queryInterface.removeIndex('builds', 'builds_type_idx');
    } catch (error) {
      // Index might not exist
    }

    // Remove column
    await queryInterface.removeColumn('builds', 'type');

    // Remove enum type
    await queryInterface.sequelize.query('DROP TYPE IF EXISTS "enum_builds_type";');
  },
};
