import { Pool } from 'pg'

const handleFunc = async (event: any) => {
  const body = await readBody(event)
  const { lineIds, orderId } = body

  if (!lineIds || !Array.isArray(lineIds) || lineIds.length === 0) {
    throw createError({
      statusCode: 400,
      message: 'lineIds array is required'
    })
  }

  if (!orderId) {
    throw createError({
      statusCode: 400,
      message: 'orderId is required'
    })
  }

  // Get PostgreSQL credentials from environment
  const config = useRuntimeConfig()
  const dbConfig = {
    host: config.pgHost,
    port: parseInt(config.pgPort || '5432'),
    database: config.pgDatabase,
    user: config.pgUser,
    password: config.pgPassword,
  }

  // Validate required credentials
  if (!dbConfig.host || !dbConfig.database || !dbConfig.user || !dbConfig.password) {
    throw createError({
      statusCode: 500,
      message: 'PostgreSQL credentials not configured. Please set PG_HOST, PG_DATABASE, PG_USER, PG_PASSWORD in .env'
    })
  }

  const pool = new Pool(dbConfig)

  try {
    // Build SQL with parameterized query to prevent SQL injection
    // Set both a_processed = 'Y' and c_order_refinv_id to the created order
    const placeholders = lineIds.map((_, i) => `$${i + 1}`).join(',')
    const sql = `UPDATE cust_fulfillmentfeeline
                 SET a_processed = 'Y', c_order_refinv_id = $${lineIds.length + 1}, updated = now()
                 WHERE cust_fulfillmentfeeline_id IN (${placeholders})`

    const result = await pool.query(sql, [...lineIds, orderId])

    return {
      success: true,
      updatedCount: result.rowCount,
      totalCount: lineIds.length,
      orderId: orderId
    }
  } catch (err: any) {
    console.error('PostgreSQL batch update error:', err)
    throw createError({
      statusCode: 500,
      message: `Database error: ${err.message}`
    })
  } finally {
    await pool.end()
  }
}

export default defineEventHandler(async (event) => {
  try {
    return await handleFunc(event)
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      return await handleFunc(event, authToken)
    } catch(error: any) {
      console.error('Fatal error in batch-process-lines:', error)
      throw error
    }
  }
})
