#!/usr/bin/env node
/**
 * ax_assignments INSERT 직접 테스트 (배열 SQL 리터럴 방식)
 */
require("dotenv").config({ path: require("path").join(__dirname, "..", ".env") });
const { Pool } = require("pg");
const { v4: uuidv4 } = require("uuid");

const pool = new Pool({
  host: process.env.DB_HOST,
  port: Number(process.env.DB_PORT || 5432),
  database: process.env.DB_DATABASE,
  user: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
});

async function main() {
  const id = uuidv4();
  const now = new Date();

  const toArrayLiteralSafe = (v) => {
    if (v === "" || typeof v === "string" || v == null) return "'{}'";
    const arr = Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
    if (arr.length === 0) return "'{}'";
    const escaped = arr.map((s) => `"${String(s).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`);
    return `'{${escaped.join(",")}}'`;
  };

  const dataTypesLit = "'{}'";
  const qualitativeLit = "'{}'";
  const techStackLit = "'{}'";
  const risksLit = "'{}'";

  const sql = `INSERT INTO ax_assignments (
    id, department, name, employee_id, position, phone, email,
    work_process_description, pain_point, current_time_spent, error_rate_before,
    collaboration_depts, reason_to_solve, ai_expectation, output_type, automation_level,
    data_readiness, data_location, personal_info, data_quality, data_count, data_types,
    time_reduction, error_reduction, volume_increase, cost_reduction, response_time,
    other_metrics, annual_savings, labor_replacement, revenue_increase, other_effects,
    qualitative_effects, tech_stack, risks, risk_detail, participation_pledge, status,
    created_at, updated_at
  ) VALUES (
    $1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16,
    $17, $18, $19, $20, $21, ${dataTypesLit}::text[], $22, $23, $24, $25, $26, $27, $28, $29, $30,
    $31, ${qualitativeLit}::text[], ${techStackLit}::text[], ${risksLit}::text[], $32, $33, $34, $35, $36
  )`;

  const params = [
    ... [id, "테스트부서", "홍길동", "", "", "", "", "테스트", "테스트", "30분", "5%", "", "테스트", "테스트", "테스트", "", "", "", "", "", "" ],
    ... [ "", "", "", "", "", "", "", "", "", "" ],
    ... [ "", false, "신청", now, now ],
  ];

  console.log("SQL preview:", sql.substring(200, 400));
  const res = await pool.query(sql, params);
  console.log("OK, inserted:", id);
  await pool.end();
}

main().catch((e) => {
  console.error("Error:", e.message);
  process.exit(1);
});
