const express = require('express');
const { Pool } = require('pg');
const cors = require('cors');
require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

// Middleware
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));

// Database Connection
const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  password: process.env.DB_PASSWORD,
  port: process.env.DB_PORT,
});

pool.on('error', (err) => {
  console.error('Unexpected error on idle client', err);
  process.exit(-1);
});

// Routes

// --- PRODUCTS ---
app.get('/api/products', async (req, res) => {
  try {
    const result = await pool.query('SELECT id, title, price, image, description, gallery as images, slug, number, aspect_ratio as "aspectRatio", details FROM products ORDER BY id ASC');
    res.json(result.rows);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

app.post('/api/products', async (req, res) => {
  const { title, price, image, description, images, slug, number, aspectRatio, details } = req.body;
  try {
    const result = await pool.query(
      'INSERT INTO products (title, price, image, description, gallery, slug, number, aspect_ratio, details) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id, title, price, image, description, gallery as images, slug, number, aspect_ratio as "aspectRatio", details',
      [title, price, image, description, JSON.stringify(images), slug, number, aspectRatio, JSON.stringify(details || [])]
    );
    res.status(201).json(result.rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

app.put('/api/products/:id', async (req, res) => {
  const { id } = req.params;
  const { title, price, image, description, images, slug, number, aspectRatio, details } = req.body;
  try {
    const result = await pool.query(
      'UPDATE products SET title = $1, price = $2, image = $3, description = $4, gallery = $5, slug = $6, number = $7, aspect_ratio = $8, details = $9 WHERE id = $10 RETURNING id, title, price, image, description, gallery as images, slug, number, aspect_ratio as "aspectRatio", details',
      [title, price, image, description, JSON.stringify(images), slug, number, aspectRatio, JSON.stringify(details || []), id]
    );
    res.json(result.rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

app.delete('/api/products/:id', async (req, res) => {
  const { id } = req.params;
  try {
    await pool.query('DELETE FROM products WHERE id = $1', [id]);
    res.json({ message: 'Product deleted' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

// --- ARTICLES ---
app.get('/api/articles', async (req, res) => {
  try {
    const result = await pool.query('SELECT id, title, date, image, sections, slug, category, description, is_featured as "isFeatured" FROM articles ORDER BY id ASC');
    res.json(result.rows);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

app.post('/api/articles', async (req, res) => {
  const { title, date, image, sections, slug, category, description, isFeatured } = req.body;
  try {
    if (isFeatured) {
        await pool.query('UPDATE articles SET is_featured = FALSE');
    }
    const result = await pool.query(
      'INSERT INTO articles (title, date, image, sections, slug, category, description, is_featured) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, title, date, image, sections, slug, category, description, is_featured as "isFeatured"',
      [title, date, image, JSON.stringify(sections), slug, category, description, !!isFeatured]
    );
    res.status(201).json(result.rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

app.put('/api/articles/:id', async (req, res) => {
  const { id } = req.params;
  const { title, date, image, sections, slug, category, description, isFeatured } = req.body;
  try {
    if (isFeatured) {
        await pool.query('UPDATE articles SET is_featured = FALSE');
    }
    const result = await pool.query(
      'UPDATE articles SET title = $1, date = $2, image = $3, sections = $4, slug = $5, category = $6, description = $7, is_featured = $8 WHERE id = $9 RETURNING id, title, date, image, sections, slug, category, description, is_featured as "isFeatured"',
      [title, date, image, JSON.stringify(sections), slug, category, description, !!isFeatured, id]
    );
    res.json(result.rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

app.delete('/api/articles/:id', async (req, res) => {
  const { id } = req.params;
  try {
    await pool.query('DELETE FROM articles WHERE id = $1', [id]);
    res.json({ message: 'Article deleted' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

// Orders API
app.get('/api/orders', async (req, res) => {
  try {
    const result = await pool.query('SELECT * FROM orders ORDER BY created_at DESC');
    res.json(result.rows);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

app.post('/api/orders', async (req, res) => {
  const { customer_email, customer_name, shipping_address, items, total_amount } = req.body;
  try {
    const result = await pool.query(
      'INSERT INTO orders (customer_email, customer_name, shipping_address, items, total_amount, payment_status) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',
      [customer_email, customer_name, JSON.stringify(shipping_address), JSON.stringify(items), total_amount, 'paid']
    );
    res.status(201).json(result.rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

app.put('/api/orders/:id/status', async (req, res) => {
  const { id } = req.params;
  const { shipping_status } = req.body;
  try {
    const result = await pool.query(
      'UPDATE orders SET shipping_status = $1 WHERE id = $2 RETURNING *',
      [shipping_status, id]
    );
    res.json(result.rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

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