import { Router, Request, Response } from 'express';
import { prisma } from '../db/prisma';
import { requireAuth, requires } from '../middleware/auth';

const router = Router();

const PUBLIC_SETTINGS = [
  'site_title',
  'site_tagline',
  'telegram_link',
  'nostr_link',
  'x_link',
  'youtube_link',
  'discord_link',
  'linkedin_link',
];

router.get(
  '/',
  requireAuth,
  requires('settings.edit'),
  async (req: Request, res: Response) => {
    try {
      const settings = await prisma.setting.findMany();
      const result: Record<string, string> = {};
      for (const s of settings) {
        result[s.key] = s.value;
      }
      res.json(result);
    } catch (err) {
      console.error('List settings error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.get('/public', async (_req: Request, res: Response) => {
  try {
    const settings = await prisma.setting.findMany({
      where: { key: { in: PUBLIC_SETTINGS } },
    });
    const result: Record<string, string> = {};
    for (const s of settings) {
      result[s.key] = s.value;
    }
    res.json(result);
  } catch (err) {
    console.error('Public settings error:', err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

router.patch(
  '/',
  requireAuth,
  requires('settings.edit'),
  async (req: Request, res: Response) => {
    try {
      const { key, value } = req.body;
      if (!key || value === undefined) {
        res.status(400).json({ error: 'key and value are required' });
        return;
      }

      const setting = await prisma.setting.upsert({
        where: { key },
        update: { value },
        create: { key, value },
      });

      res.json(setting);
    } catch (err) {
      console.error('Update setting error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

export default router;
