'use strict'

const { execute } = require('../database/postgres')

class WhatsappLog {
  static async create({ user_id, phone, type, payload, tenant_id }) {
    const jsonPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload
    return execute(
      `INSERT INTO whatsapp_logs (user_id, phone, type, payload, tenant_id)
       VALUES ($1, $2, $3, $4, $5) RETURNING id`,
      [user_id || null, phone, type, jsonPayload, tenant_id || 1]
    )
  }

  static async updateStatus(id, status, responseData = null) {
    const jsonResponse = responseData && typeof responseData === 'object'
      ? JSON.stringify(responseData)
      : responseData
    return execute(
      `UPDATE whatsapp_logs SET status=$1, response=$2, updated_at=NOW() WHERE id=$3`,
      [status, jsonResponse, id]
    )
  }
}

module.exports = WhatsappLog
