/**
 * DB 시더: 테스터 계정 생성
 * 실행: node e2e/helpers/db-seed.js
 */
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');

const DB_CONFIG = {
  host: '3.36.27.239',
  port: 3306,
  user: 'root',
  password: 'ssadm!#@$',
  database: 'jongryangje_dev',
};

const TEST_PASSWORD = 'test1234!';

const TEST_ACCOUNTS = [
  { id: 'tester_admin', name: '테스터관리자', email: 'tester_admin@test.com', phone: '010-0000-0001', level: 4, lg_idx: null },
  { id: 'tester_local', name: '테스터지자체', email: 'tester_local@test.com', phone: '010-0000-0002', level: 3, lg_idx: 1 },
  { id: 'tester_shop',  name: '테스터판매소', email: 'tester_shop@test.com',  phone: '010-0000-0003', level: 2, lg_idx: null },
  { id: 'tester_user',  name: '테스터사용자', email: 'tester_user@test.com',  phone: '010-0000-0004', level: 1, lg_idx: null },
];

async function seed() {
  const conn = await mysql.createConnection(DB_CONFIG);
  const hash = bcrypt.hashSync(TEST_PASSWORD, 10).replace('$2b$', '$2y$');

  console.log('테스터 계정 시딩 시작...');

  for (const acct of TEST_ACCOUNTS) {
    // Upsert member
    await conn.execute(
      `INSERT INTO member (mb_id, mb_passwd, mb_name, mb_email, mb_phone, mb_lang, mb_level, mb_group, mb_lg_idx, mb_state, mb_regdate)
       VALUES (?, ?, ?, ?, ?, 'ko', ?, '', ?, 1, NOW())
       ON DUPLICATE KEY UPDATE mb_passwd = VALUES(mb_passwd), mb_state = 1, mb_level = VALUES(mb_level)`,
      [acct.id, hash, acct.name, acct.email, acct.phone, acct.level, acct.lg_idx]
    );

    // Ensure approval request exists (approved)
    const [rows] = await conn.execute(
      'SELECT mb_idx FROM member WHERE mb_id = ?', [acct.id]
    );
    if (rows.length > 0) {
      const mbIdx = rows[0].mb_idx;
      const [existing] = await conn.execute(
        'SELECT mar_idx FROM member_approval_request WHERE mb_idx = ?', [mbIdx]
      );
      if (existing.length === 0) {
        await conn.execute(
          `INSERT INTO member_approval_request (mb_idx, mar_requested_level, mar_status, mar_request_note, mar_requested_at, mar_processed_at)
           VALUES (?, ?, 'approved', '테스트 계정 자동 승인', NOW(), NOW())`,
          [mbIdx, acct.level]
        );
      }
    }

    console.log(`  ✓ ${acct.id} (Level ${acct.level})`);
  }

  await conn.end();
  console.log('시딩 완료!');
}

seed().catch(err => {
  console.error('시딩 실패:', err.message);
  process.exit(1);
});
