
/**
 * @param { import("knex").Knex } knex
 * @returns { Promise<void> }
 */
exports.up = async function (knex) {
    const hasHireDate = await knex.schema.hasColumn('workers', 'hire_date');

    if (!hasHireDate) {
        await knex.schema.alterTable('workers', function (table) {
            // Modify status to ENUM
            // Note: Knex might not support modifying to ENUM easily across DBs, but valid for MySQL
            // We use raw SQL for status modification to be safe with existing data

            // Add new columns
            table.string('phone_number', 20).nullable().comment('전화번호');
            table.string('email', 100).nullable().comment('이메일');
            table.date('hire_date').nullable().comment('입사일');
            table.string('department', 100).nullable().comment('부서');
            table.text('notes').nullable().comment('비고');
        });

        // Update status column using raw query
        await knex.raw(`
      ALTER TABLE workers 
      MODIFY COLUMN status ENUM('active', 'inactive') DEFAULT 'active' COMMENT '작업자 상태 (active: 활성, inactive: 비활성)'
    `);

        // Add indexes
        await knex.raw(`CREATE INDEX IF NOT EXISTS idx_workers_status ON workers(status)`);
        await knex.raw(`CREATE INDEX IF NOT EXISTS idx_workers_hire_date ON workers(hire_date)`);

        // Set NULL status to active
        await knex('workers').whereNull('status').update({ status: 'active' });
    }
};

/**
 * @param { import("knex").Knex } knex
 * @returns { Promise<void> }
 */
exports.down = async function (knex) {
    // We generally don't want to lose data on rollback of this critical schema fix,
    // but technically we should revert changes.
    // For safety, we might skip dropping columns or implement it carefully.

    const hasHireDate = await knex.schema.hasColumn('workers', 'hire_date');
    if (hasHireDate) {
        await knex.schema.alterTable('workers', function (table) {
            table.dropColumn('phone_number');
            table.dropColumn('email');
            table.dropColumn('hire_date');
            table.dropColumn('department');
            table.dropColumn('notes');
        });

        await knex.raw(`
       ALTER TABLE workers 
       MODIFY COLUMN status VARCHAR(20) DEFAULT 'active' COMMENT '상태 (active, inactive)'
     `);
    }
};
