// Supra Theme - JavaScript Example
// This file demonstrates syntax highlighting for JavaScript

const express = require("express");
const { createClient } = require("@supabase/supabase-js");

class DatabaseService {
  constructor(apiKey, url) {
    this.supabase = createClient(url, apiKey);
    this.isConnected = false;
  }

  async connect() {
    try {
      const { data, error } = await this.supabase
        .from("users")
        .select("*")
        .limit(10);

      if (error) throw error;

      this.isConnected = true;
      console.log("Connected to database successfully");
      return data;
    } catch (err) {
      console.error("Database connection failed:", err.message);
      throw err;
    }
  }

  async createUser(userData) {
    const { name, email, age } = userData;

    if (!name || !email) {
      throw new Error("Name and email are required");
    }

    const { data, error } = await this.supabase
      .from("users")
      .insert([{ name, email, age: age || null }])
      .select();

    if (error) throw error;
    return data[0];
  }
}

// Arrow functions and async/await
const initializeApp = async () => {
  const app = express();
  const port = process.env.PORT || 3000;

  const db = new DatabaseService(
    process.env.SUPABASE_API_KEY,
    process.env.SUPABASE_URL
  );

  app.use(express.json());

  app.get("/users", async (req, res) => {
    try {
      const users = await db.connect();
      res.json({ success: true, data: users });
    } catch (error) {
      res.status(500).json({
        success: false,
        error: error.message,
      });
    }
  });

  app.listen(port, () => {
    console.log(`Server running on port ${port}`);
  });
};

// Template literals and destructuring
const config = {
  database: {
    host: "localhost",
    port: 5432,
    name: "supra_db",
  },
  api: {
    version: "v1",
    rateLimit: 1000,
  },
};

const { database, api } = config;
const connectionString = `postgresql://${database.host}:${database.port}/${database.name}`;

// Export for module usage
module.exports = {
  DatabaseService,
  initializeApp,
  config,
};
