import { Router, Response, Request } from 'express';
import { PrivacyPage } from '../models/index.js';
import { authenticate, requireRole, AuthRequest } from '../middleware/auth.js';

const router = Router();

const defaultSections = [
  {
    title: { en: '1. Data Collection', zh: '1. 資料收集' },
    content: {
      en: '<p>Golf Lifestyle Group Limited ("the Company") is committed to protecting your personal data privacy. This privacy policy explains how we collect, use, disclose and protect your personal information.</p><p>When you use our services, register as a member, or browse our website, we may collect the following information:</p><ul><li>Name and contact details (email, phone number, address)</li><li>Golf ID membership information</li><li>Service usage records</li></ul>',
      zh: '<p>高球品味集團有限公司（「本公司」）致力保障您的個人資料私隱。本私隱政策說明本公司如何收集、使用、披露及保護您的個人資料。</p><p>當您使用我們的服務、登記成為會員或瀏覽我們的網站時，我們可能會收集以下資料：</p><ul><li>姓名及聯絡資料（電郵、電話號碼、地址）</li><li>高球証會員資料</li><li>使用服務之紀錄</li></ul>',
    },
  },
  {
    title: { en: '2. Use of Data', zh: '2. 資料使用' },
    content: {
      en: '<p>We use collected information to:</p><ul><li>Provide and manage our services</li><li>Process your membership registration and offer redemptions</li><li>Send you promotional materials and offer notifications</li><li>Improve our services and user experience</li></ul>',
      zh: '<p>我們使用所收集的資料以：</p><ul><li>提供及管理我們的服務</li><li>處理您的會員登記及優惠兌換</li><li>向您發送推廣資訊及優惠通知</li><li>改善我們的服務及用戶體驗</li></ul>',
    },
  },
  {
    title: { en: '3. Contact Us', zh: '3. 聯絡我們' },
    content: {
      en: '<p>For any enquiries regarding this privacy policy, please contact:</p><p>Email: marketing@glg.com.hk<br>Phone: (852) 3582-3088</p>',
      zh: '<p>如對本私隱政策有任何查詢，請聯絡：</p><p>電郵：marketing@glg.com.hk<br>電話：(852) 3582-3088</p>',
    },
  },
];

const defaultData = {
  heroTitle: { en: 'Privacy Statement', zh: '私隱政策' },
  heroSubtitle: {
    en: 'How we collect, use and protect your personal information.',
    zh: '我們如何收集、使用及保護您的個人資料。',
  },
  sections: defaultSections,
};

router.get('/', async (req: Request, res: Response): Promise<void> => {
  try {
    let doc = await PrivacyPage.findOne();

    if (!doc) {
      doc = new PrivacyPage(defaultData);
      await doc.save();
    }

    res.json(doc);
  } catch (error) {
    console.error('Error fetching privacy page:', error);
    res.status(500).json({ error: 'Server error' });
  }
});

router.put(
  '/',
  authenticate,
  requireRole('admin'),
  async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      let doc = await PrivacyPage.findOne();

      if (!doc) {
        doc = new PrivacyPage(req.body);
      } else {
        Object.assign(doc, req.body);
      }

      await doc.save();
      res.json(doc);
    } catch (error) {
      console.error('Error updating privacy page:', error);
      res.status(500).json({ error: 'Server error' });
    }
  }
);

export default router;
