'use strict'

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

class ClubPayment {
  static create({ member_id, plan_id, amount, status = 'pending', asaas_payment_id, reference_month }) {
    return execute(
      `INSERT INTO club_payments
         (member_id, plan_id, amount, status, asaas_payment_id, reference_month)
       VALUES ($1,$2,$3,$4,$5,$6) RETURNING id`,
      [member_id, plan_id, amount, status, asaas_payment_id || null, reference_month || null]
    )
  }

  static findByMember(memberId) {
    return query(
      `SELECT * FROM club_payments WHERE member_id=$1 ORDER BY created_at DESC`,
      [memberId]
    )
  }

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

  static updateStatus(id, status, paidAt = null) {
    return execute(
      `UPDATE club_payments SET status=$1, paid_at=$2 WHERE id=$3`,
      [status, paidAt, id]
    )
  }

  static listByClub(clubId, { limit = 100, offset = 0 } = {}) {
    return query(
      `SELECT cp.*, cm.user_cpf, cm.user_nome, pl.name AS plan_name
       FROM club_payments cp
       JOIN club_members cm ON cm.id = cp.member_id
       JOIN club_plans pl ON pl.id = cp.plan_id
       WHERE cm.club_id = $1
       ORDER BY cp.created_at DESC LIMIT $2 OFFSET $3`,
      [clubId, limit, offset]
    )
  }
}

module.exports = ClubPayment
