#!/usr/bin/env node
const http = require("http");
const { Client } = require("pg");

const PORT = 5001;

const client = new Client({
  host: "localhost",
  port: 5432,
  database: "skyartshop",
  user: "skyartapp",
  password: "SkyArt2025Pass!"
});

client.connect().catch(err => {
  console.error("Database connection error:", err);
  process.exit(1);
});

const server = http.createServer(async (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type");
  res.setHeader("Content-Type", "application/json");

  if (req.method === "OPTIONS") {
    res.writeHead(200);
    res.end();
    return;
  }

  const match = req.url.match(/^\/api\/variants\/([a-f0-9-]+)$/i);
  
  if (!match) {
    res.writeHead(404);
    res.end(JSON.stringify({ error: "Not found" }));
    return;
  }

  const productId = match[1];

  try {
    const result = await client.query(
      "SELECT variants FROM products WHERE id = $1",
      [productId]
    );

    if (result.rows.length === 0) {
      res.writeHead(404);
      res.end(JSON.stringify({ error: "Product not found" }));
      return;
    }

    const variants = result.rows[0].variants || [];
    res.writeHead(200);
    res.end(JSON.stringify(variants));
  } catch (error) {
    console.error("Query error:", error);
    res.writeHead(500);
    res.end(JSON.stringify({ error: "Internal server error" }));
  }
});

server.listen(PORT, "127.0.0.1", () => {
  console.log(`Variant API running on http://127.0.0.1:${PORT}`);
});

process.on("SIGTERM", () => {
  server.close(() => {
    client.end();
    process.exit(0);
  });
});
