import mysql from 'mysql2/promise';
import dotenv from 'dotenv';

dotenv.config();

const { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT } = process.env;

async function initDB() {
  const connection = await mysql.createConnection({
    host: DB_HOST,
    user: DB_USER,
    password: DB_PASS,
    database: DB_NAME,
    port: parseInt(DB_PORT || '3306'),
    multipleStatements: true
  });

  console.log('🔄 DB 초기화 시작 (표준화 스키마 적용)...');

  // 기존 테이블 삭제
  const tablesToDrop = [
    'pc_assets', 'server_assets', 'storage_assets', 'equip_assets', 'mobile_assets', 
    'sw_sub_assets', 'sw_perm_assets', 'cloud_assets', 'sw_users', 'asset_logs'
  ];
  for (const table of tablesToDrop) {
    await connection.query(`DROP TABLE IF EXISTS ${table}`);
  }

  // 공통 하드웨어 테이블 생성 함수
  const createHardwareTable = (tableName, comment) => `
    CREATE TABLE ${tableName} (
      id VARCHAR(50) PRIMARY KEY,
      corp VARCHAR(100) COMMENT '구매법인',
      asset_code VARCHAR(100) COMMENT '자산번호',
      purchase_date VARCHAR(50) COMMENT '구매연월',
      type VARCHAR(50) COMMENT '유형',
      detail_purpose VARCHAR(50) COMMENT '상세용도',
      purpose VARCHAR(255) COMMENT '용도',
      details TEXT COMMENT '상세내용',
      current_org VARCHAR(255) COMMENT '현 사용조직',
      prev_org VARCHAR(255) COMMENT '이전 사용조직',
      location VARCHAR(255) COMMENT '설치위치',
      manager_main VARCHAR(100) COMMENT '담당자(정)',
      manager_sub VARCHAR(100) COMMENT '담당자(부)',
      ip_address VARCHAR(100) COMMENT 'IP 주소 1',
      remote_tool VARCHAR(100) COMMENT '원격도구',
      server_id VARCHAR(100),
      server_pw VARCHAR(100),
      model_name VARCHAR(255),
      os VARCHAR(100),
      cpu VARCHAR(255),
      ram VARCHAR(100),
      gpu VARCHAR(100),
      storage1 VARCHAR(255),
      storage2 VARCHAR(255),
      storage3 VARCHAR(255),
      monitoring VARCHAR(100),
      price VARCHAR(100) COMMENT '금액',
      remarks TEXT,
      storage_location VARCHAR(255) COMMENT '보관위치',
      status VARCHAR(50) COMMENT '현재상태',
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='${comment}';
  `;

  await connection.query(createHardwareTable('pc_assets', '개인PC 자산'));
  await connection.query(createHardwareTable('server_assets', '서버 자산'));
  await connection.query(createHardwareTable('storage_assets', '스토리지 자산'));
  await connection.query(createHardwareTable('equip_assets', '전산비품 자산'));
  await connection.query(createHardwareTable('mobile_assets', '모바일기기 자산'));

  // 소프트웨어 구독 테이블
  await connection.query(`
    CREATE TABLE sw_sub_assets (
      id VARCHAR(50) PRIMARY KEY,
      corp VARCHAR(100) COMMENT '구매법인',
      asset_code VARCHAR(100) COMMENT '자산번호',
      product_name VARCHAR(255) COMMENT '제품명',
      license_type VARCHAR(100) COMMENT '라이선스 유형',
      quantity INT COMMENT '수량',
      price VARCHAR(100) COMMENT '금액',
      purchase_date VARCHAR(50) COMMENT '구매연월',
      expiry_date VARCHAR(50) COMMENT '만료일',
      vendor VARCHAR(255) COMMENT '납품업체',
      remarks TEXT COMMENT '비고',
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  `);

  // 소프트웨어 영구 테이블
  await connection.query(`
    CREATE TABLE sw_perm_assets (
      id VARCHAR(50) PRIMARY KEY,
      corp VARCHAR(100) COMMENT '구매법인',
      asset_code VARCHAR(100) COMMENT '자산번호',
      product_name VARCHAR(255) COMMENT '제품명',
      license_key VARCHAR(255) COMMENT '라이선스 키',
      quantity INT COMMENT '수량',
      price VARCHAR(100) COMMENT '금액',
      purchase_date VARCHAR(50) COMMENT '구매연월',
      vendor VARCHAR(255) COMMENT '납품업체',
      remarks TEXT COMMENT '비고',
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  `);

  // 클라우드 자산 테이블
  await connection.query(`
    CREATE TABLE cloud_assets (
      id VARCHAR(50) PRIMARY KEY,
      platform_name VARCHAR(100),
      corp VARCHAR(100),
      dept VARCHAR(100),
      product_name VARCHAR(255),
      account_name VARCHAR(255),
      pay_method VARCHAR(100),
      pay_day VARCHAR(50),
      card_num VARCHAR(100),
      monthly_fee VARCHAR(100),
      remarks TEXT,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  `);

  // 소프트웨어 사용자 매핑 테이블
  await connection.query(`
    CREATE TABLE sw_users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      sw_id VARCHAR(50) COMMENT 'SW 자산 ID',
      corp VARCHAR(100) COMMENT '법인',
      dept VARCHAR(100) COMMENT '부서',
      position VARCHAR(50) COMMENT '직위',
      user_name VARCHAR(100) COMMENT '이름',
      usage_period VARCHAR(100) COMMENT '사용기간',
      doc_name VARCHAR(255) COMMENT '신청서명',
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  `);

  // 변경 이력 테이블
  await connection.query(`
    CREATE TABLE asset_logs (
      id VARCHAR(50) PRIMARY KEY,
      asset_id VARCHAR(50),
      log_date VARCHAR(50),
      log_user VARCHAR(100),
      details TEXT,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  `);

  console.log('✅ 모든 테이블이 표준화된 스키마로 재생성되었습니다.');
  await connection.end();
}

initDB().catch(err => {
  console.error('❌ DB 초기화 실패:', err);
  process.exit(1);
});
