/**
 * 마이그레이션: TBM 기반 작업보고서의 work_type_id를 task_id로 수정
 *
 * 문제: TBM에서 작업보고서 생성 시 work_type_id(공정 ID)가 저장됨
 * 해결: tbm_team_assignments 테이블의 task_id로 업데이트
 *
 * 실행: node db/migrations/20260205_fix_work_type_id_data.js
 */

const { getDb } = require('../../dbPool');

async function migrate() {
  const db = await getDb();


  try {
    // 1. 수정 대상 확인 (TBM 기반이면서 work_type_id가 task_id와 다른 경우)
    const [checkResult] = await db.query(`
      SELECT
        dwr.id,
        dwr.work_type_id as current_work_type_id,
        ta.task_id as correct_task_id,
        ta.work_type_id as tbm_work_type_id,
        w.worker_name,
        dwr.report_date
      FROM daily_work_reports dwr
      INNER JOIN tbm_team_assignments ta ON dwr.tbm_assignment_id = ta.assignment_id
      INNER JOIN workers w ON dwr.worker_id = w.worker_id
      WHERE dwr.tbm_assignment_id IS NOT NULL
        AND ta.task_id IS NOT NULL
        AND dwr.work_type_id != ta.task_id
      ORDER BY dwr.report_date DESC
    `);


    if (checkResult.length === 0) {
      return;
    }

    // 수정 대상 샘플 출력
    console.log('─'.repeat(80));
    checkResult.slice(0, 10).forEach(row => {
      console.log(`  ID: ${row.id} | ${row.worker_name} | ${row.report_date}`);
      console.log(`    현재 work_type_id: ${row.current_work_type_id} → 올바른 task_id: ${row.correct_task_id}`);
    });
    if (checkResult.length > 10) {
      console.log(`  ... 외 ${checkResult.length - 10}개`);
    }
    console.log('─'.repeat(80));

    // 2. 업데이트 실행
    const [updateResult] = await db.query(`
      UPDATE daily_work_reports dwr
      INNER JOIN tbm_team_assignments ta ON dwr.tbm_assignment_id = ta.assignment_id
      SET dwr.work_type_id = ta.task_id
      WHERE dwr.tbm_assignment_id IS NOT NULL
        AND ta.task_id IS NOT NULL
        AND dwr.work_type_id != ta.task_id
    `);


    // 3. 수정 결과 확인
    const [verifyResult] = await db.query(`
      SELECT
        dwr.id,
        dwr.work_type_id,
        ta.task_id,
        t.task_name,
        wt.name as work_type_name
      FROM daily_work_reports dwr
      INNER JOIN tbm_team_assignments ta ON dwr.tbm_assignment_id = ta.assignment_id
      LEFT JOIN tasks t ON dwr.work_type_id = t.task_id
      LEFT JOIN work_types wt ON t.work_type_id = wt.id
      WHERE dwr.tbm_assignment_id IS NOT NULL
      LIMIT 5
    `);

    console.log('─'.repeat(80));
    verifyResult.forEach(row => {
      console.log(`  ID: ${row.id} | work_type_id: ${row.work_type_id} | task: ${row.task_name || 'N/A'} | 공정: ${row.work_type_name || 'N/A'}`);
    });
    console.log('─'.repeat(80));

  } catch (error) {
    console.error(' 마이그레이션 실패:', error.message);
    throw error;
  }
}

// 실행
migrate()
  .then(() => {
    process.exit(0);
  })
  .catch(err => {
    console.error('\n 마이그레이션 실패:', err);
    process.exit(1);
  });
