'use strict'

const https = require('https')

const ASAAS_URL = process.env.ASAAS_URL || 'https://sandbox.asaas.com/api/v3'

function asaasRequest(method, path, body = null, apiKey = null) {
  const key = apiKey || process.env.ASAAS_API_KEY || ''
  return new Promise((resolve, reject) => {
    const url = new URL(`${ASAAS_URL}${path}`)
    const options = {
      hostname: url.hostname,
      port: 443,
      path: url.pathname + url.search,
      method,
      headers: {
        'access_token': key,
        'Content-Type': 'application/json',
      },
    }

    const req = https.request(options, (res) => {
      let data = ''
      res.on('data', chunk => data += chunk)
      res.on('end', () => {
        try {
          const parsed = JSON.parse(data)
          if (res.statusCode >= 400) reject(new Error(parsed.errors?.[0]?.description || `Asaas error ${res.statusCode}`))
          else resolve(parsed)
        } catch (e) {
          reject(new Error('Invalid Asaas response'))
        }
      })
    })

    req.on('error', reject)
    if (body) req.write(JSON.stringify(body))
    req.end()
  })
}

const ClubAsaasService = {
  // Cria ou localiza cliente no Asaas
  async createCustomer({ cpf, name, phone, email, apiKey }) {
    const clean = cpf.replace(/\D/g, '')
    const existing = await asaasRequest('GET', `/customers?cpfCnpj=${clean}&limit=1`, null, apiKey)
    if (existing.data?.length > 0) return existing.data[0]

    return asaasRequest('POST', '/customers', {
      name,
      cpfCnpj: clean,
      mobilePhone: phone?.replace(/\D/g, '') || undefined,
      email: email || undefined,
    }, apiKey)
  },

  // Cria assinatura mensal no Asaas
  async createSubscription({ customerId, value, description, nextDueDate, apiKey }) {
    return asaasRequest('POST', '/subscriptions', {
      customer: customerId,
      billingType: 'PIX',
      value: Number(value),
      nextDueDate,
      cycle: 'MONTHLY',
      description,
      maxPayments: 0,
    }, apiKey)
  },

  // Cancela assinatura
  async cancelSubscription(subscriptionId, apiKey) {
    return asaasRequest('DELETE', `/subscriptions/${subscriptionId}`, null, apiKey)
  },

  // Suspende cobranças (pausa)
  async suspendSubscription(subscriptionId, apiKey) {
    return asaasRequest('POST', `/subscriptions/${subscriptionId}/suspend`, null, apiKey)
  },

  // Reativa assinatura suspensa
  async reactivateSubscription(subscriptionId, apiKey) {
    return asaasRequest('POST', `/subscriptions/${subscriptionId}/reactivate`, null, apiKey)
  },

  // Lista pagamentos de uma assinatura
  async listPayments(subscriptionId, apiKey) {
    return asaasRequest('GET', `/payments?subscription=${subscriptionId}&limit=12`, null, apiKey)
  },

  // Detalhe de um pagamento
  async getPayment(paymentId, apiKey) {
    return asaasRequest('GET', `/payments/${paymentId}`, null, apiKey)
  },
}

module.exports = ClubAsaasService
