/**
 * Migration: Create vacation_requests table
 * Purpose: Track vacation request workflow (request, approval/rejection)
 * Date: 2026-01-29
 */

exports.up = async function(knex) {
  // Create vacation_requests table
  await knex.schema.createTable('vacation_requests', (table) => {
    table.increments('request_id').primary().comment('휴가 신청 ID');

    // 작업자 정보
    table.integer('worker_id').notNullable().comment('작업자 ID');
    table.foreign('worker_id').references('worker_id').inTable('workers').onDelete('CASCADE');

    // 휴가 정보
    table.integer('vacation_type_id').unsigned().notNullable().comment('휴가 유형 ID');
    table.foreign('vacation_type_id').references('id').inTable('vacation_types').onDelete('RESTRICT');

    table.date('start_date').notNullable().comment('휴가 시작일');
    table.date('end_date').notNullable().comment('휴가 종료일');
    table.decimal('days_used', 4, 1).notNullable().comment('사용 일수 (0.5일 단위)');

    table.text('reason').nullable().comment('휴가 사유');

    // 신청 및 승인 정보
    table.enum('status', ['pending', 'approved', 'rejected'])
      .notNullable()
      .defaultTo('pending')
      .comment('승인 상태: pending(대기), approved(승인), rejected(거부)');

    table.integer('requested_by').notNullable().comment('신청자 user_id');
    table.foreign('requested_by').references('user_id').inTable('users').onDelete('RESTRICT');

    table.integer('reviewed_by').nullable().comment('승인/거부자 user_id');
    table.foreign('reviewed_by').references('user_id').inTable('users').onDelete('SET NULL');

    table.timestamp('reviewed_at').nullable().comment('승인/거부 일시');
    table.text('review_note').nullable().comment('승인/거부 메모');

    // 타임스탬프
    table.timestamp('created_at').defaultTo(knex.fn.now()).comment('신청 일시');
    table.timestamp('updated_at').defaultTo(knex.fn.now()).comment('수정 일시');

    // 인덱스
    table.index('worker_id', 'idx_vacation_requests_worker');
    table.index('status', 'idx_vacation_requests_status');
    table.index(['start_date', 'end_date'], 'idx_vacation_requests_dates');
  });

};

exports.down = async function(knex) {
  await knex.schema.dropTableIfExists('vacation_requests');
};
