/**
 * 실제와 같은 시범 데이터 시딩 스크립트
 * 유저(member) 테이블 제외 — 모든 업무 테이블에 대구 남구청 기준 데이터 삽입
 *
 * 실행: node e2e/helpers/db-seed-realistic.js
 */
const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// .env 파일에서 DB 설정 읽기
function loadEnv() {
  const envPath = path.join(__dirname, '../../.env');
  const lines = fs.readFileSync(envPath, 'utf8').split('\n');
  const cfg = {};
  for (const line of lines) {
    const m = line.match(/^database\.default\.(\w+)\s*=\s*(.+)$/);
    if (m) cfg[m[1]] = m[2].trim();
  }
  return cfg;
}

async function main() {
  const env = loadEnv();
  const conn = await mysql.createConnection({
    host: env.hostname,
    port: parseInt(env.port || '3306'),
    user: env.username,
    password: env.password,
    database: env.database,
    multipleStatements: true,
  });

  console.log('DB 연결 성공:', env.hostname);

  // 남구청 lg_idx 가져오기
  const [[lgRow]] = await conn.query("SELECT lg_idx FROM local_government WHERE lg_code = '110204' LIMIT 1");
  if (!lgRow) {
    console.error('남구청(110204) 데이터가 없습니다. local_government_init_daegu.sql을 먼저 실행하세요.');
    process.exit(1);
  }
  const LG = lgRow.lg_idx;
  console.log(`남구청 lg_idx = ${LG}`);

  // 기존 시드 데이터 정리 (idempotent)
  console.log('기존 시드 데이터 정리...');
  await conn.query(`DELETE FROM bag_issue WHERE bi2_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM bag_sale WHERE bs_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM shop_order_item WHERE soi_so_idx IN (SELECT so_idx FROM shop_order WHERE so_lg_idx = ?)`, [LG]);
  await conn.query(`DELETE FROM shop_order WHERE so_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM bag_inventory WHERE bi_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM bag_receiving WHERE br_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM bag_order_item WHERE boi_bo_idx IN (SELECT bo_idx FROM bag_order WHERE bo_lg_idx = ?)`, [LG]);
  await conn.query(`DELETE FROM bag_order WHERE bo_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM free_recipient WHERE fr_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM manager WHERE mg_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM company WHERE cp_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM sales_agency WHERE sa_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM bag_price WHERE bp_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM packaging_unit WHERE pu_lg_idx = ?`, [LG]);
  await conn.query(`DELETE FROM designated_shop WHERE ds_lg_idx = ?`, [LG]);

  // SQL 파일 읽어서 실행 (변수 치환)
  let sql = fs.readFileSync(path.join(__dirname, '../../writable/database/seed_realistic_data.sql'), 'utf8');

  // SET @LG_IDX 문을 실제 값으로 치환
  sql = sql.replace(/SET @LG_IDX = \(SELECT.*?\);/s, `SET @LG_IDX = ${LG};`);

  await conn.query(sql);
  console.log('시드 데이터 삽입 완료!');

  // 확인
  const tables = ['designated_shop', 'sales_agency', 'company', 'manager', 'free_recipient', 'bag_price', 'packaging_unit', 'bag_order', 'bag_order_item', 'bag_receiving', 'bag_inventory', 'shop_order', 'bag_sale', 'bag_issue'];
  for (const t of tables) {
    let where = '';
    if (t === 'bag_order_item') where = `WHERE boi_bo_idx IN (SELECT bo_idx FROM bag_order WHERE bo_lg_idx = ${LG})`;
    else if (t === 'shop_order_item') where = `WHERE soi_so_idx IN (SELECT so_idx FROM shop_order WHERE so_lg_idx = ${LG})`;
    else {
      const prefix = t.split('_').map(w => w[0]).join('');
      // Try common patterns
      const col = t === 'designated_shop' ? 'ds_lg_idx' :
                  t === 'sales_agency' ? 'sa_lg_idx' :
                  t === 'company' ? 'cp_lg_idx' :
                  t === 'manager' ? 'mg_lg_idx' :
                  t === 'free_recipient' ? 'fr_lg_idx' :
                  t === 'bag_price' ? 'bp_lg_idx' :
                  t === 'packaging_unit' ? 'pu_lg_idx' :
                  t === 'bag_order' ? 'bo_lg_idx' :
                  t === 'bag_receiving' ? 'br_lg_idx' :
                  t === 'bag_inventory' ? 'bi_lg_idx' :
                  t === 'shop_order' ? 'so_lg_idx' :
                  t === 'bag_sale' ? 'bs_lg_idx' :
                  t === 'bag_issue' ? 'bi2_lg_idx' : null;
      if (col) where = `WHERE ${col} = ${LG}`;
    }
    const [[{ cnt }]] = await conn.query(`SELECT COUNT(*) as cnt FROM ${t} ${where}`);
    console.log(`  ${t}: ${cnt}건`);
  }

  await conn.end();
  console.log('\n완료!');
}

main().catch(e => { console.error(e); process.exit(1); });
