const express = require('express');
const router = express.Router();
const db = require('../db');

const AD_POSITION_SPECS = {
  top: { label: 'Top Banner', width: 1180, height: 170 },
  sidebar: { label: 'Sidebar', width: 300, height: 580 },
  'mid-grid': { label: 'Mid Grid', width: 1180, height: 170 },
  'article-below-tags': { label: 'Article Below Tags', width: 776, height: 170 }
};

router.get('/placements', (req, res) => {
  res.json(AD_POSITION_SPECS);
});

// GET /api/ads - Active ads by position
router.get('/', (req, res) => {
  const { position } = req.query;
  try {
    let query = 'SELECT * FROM advertisements WHERE is_active = 1';
    const params = [];
    if (position) {
      query += ' AND position = ?';
      params.push(position);
    }
    let ads = db.prepare(query).all(...params).map((ad) => {
      const spec = AD_POSITION_SPECS[ad.position];
      return {
        ...ad,
        width: ad.width || (spec ? spec.width : null),
        height: ad.height || (spec ? spec.height : null)
      };
    });
    // Placement return rules:
    // - top/sidebar: single active ad
    // - mid-grid: up to 3 active ads
    // - article-below-tags: multiple active ads allowed
    if (position === 'top' || position === 'sidebar') {
      ads = ads.slice(0, 1);
    } else if (position === 'mid-grid') {
      ads = ads.slice(0, 3);
    }
    res.json(ads);
  } catch (err) {
    res.status(500).json({ error: 'އިޝްތިހާރުތައް ހޯދުމުގައި މައްސަލައެއް ދިމާވެއްޖެ' });
  }
});

module.exports = router;
