'use strict'

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

class Order {
  static async create({ id, customer_id, user_cpf, total_amount, payment_method, asaas_payment_id, qr_code_url, pix_copy_paste }) {
    return execute(
      `INSERT INTO orders (id, customer_id, user_cpf, total_amount, status, payment_method, asaas_payment_id, qr_code_url, pix_copy_paste)
       VALUES ($1, $2, $3, $4, 'pending', $5, $6, $7, $8) RETURNING id`,
      [id, customer_id || null, user_cpf, total_amount, payment_method || 'PIX', asaas_payment_id || null, qr_code_url || null, pix_copy_paste || null]
    )
  }

  static async updateAsaasPayment(id, asaas_payment_id, qr_code_url, pix_copy_paste) {
    return execute(
      `UPDATE orders SET asaas_payment_id=$1, qr_code_url=$2, pix_copy_paste=$3 WHERE id=$4`,
      [asaas_payment_id, qr_code_url, pix_copy_paste, id]
    )
  }

  static findByAsaasId(asaas_payment_id) {
    return queryOne('SELECT * FROM orders WHERE asaas_payment_id = $1', [asaas_payment_id])
  }

  static findById(id) {
    return queryOne('SELECT * FROM orders WHERE id = $1', [id])
  }

  static async updateStatus(id, newStatus) {
    return execute(
      `UPDATE orders SET status = $1, updated_at = NOW() WHERE id = $2`,
      [newStatus, id]
    )
  }

  static async delete(id) {
    return execute(`DELETE FROM orders WHERE id = $1`, [id])
  }
}

module.exports = Order
