const db = require('../database/db');

class Inscricao {
    static criarTabela(callback) {
      const sql = `
        CREATE TABLE IF NOT EXISTS inscricoes (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          nome TEXT NOT NULL,
          telefone TEXT NOT NULL,
          email TEXT NOT NULL UNIQUE,
          turma TEXT NOT NULL,
          data_inscricao DATETIME DEFAULT CURRENT_TIMESTAMP,
          pago BOOLEAN DEFAULT 0
        )
      `;
      
      db.run(sql, callback);
    }

  static async criar(nome, telefone, email, turma) {
    return new Promise((resolve, reject) => {
      db.run(
        `INSERT INTO inscricoes (nome, telefone, email, turma) VALUES (?, ?, ?, ?)`,
        [nome, telefone, email, turma],
        function(err) {
          if (err) {
            reject(err);
          } else {
            resolve(this.lastID);
          }
        }
      );
    });
  }

  static async buscarPorEmail(email) {
    return new Promise((resolve, reject) => {
      db.get(
        `SELECT * FROM inscricoes WHERE email = ?`,
        [email],
        (err, row) => {
          if (err) {
            reject(err);
          } else {
            resolve(row);
          }
        }
      );
    });
  }

  static async listarTodos() {
    return new Promise((resolve, reject) => {
      db.all(
        `SELECT * FROM inscricoes ORDER BY data_inscricao DESC`,
        [],
        (err, rows) => {
          if (err) {
            reject(err);
          } else {
            resolve(rows);
          }
        }
      );
    });
  }

  static async marcarComoPago(id) {
    return new Promise((resolve, reject) => {
      db.run(
        `UPDATE inscricoes SET pago = 1 WHERE id = ?`,
        [id],
        function(err) {
          if (err) {
            reject(err);
          } else {
            resolve(this.changes);
          }
        }
      );
    });
  }
}

module.exports = Inscricao;