/**
 * Super Admin — Terms of Service Content — /api/super-admin/terms-of-service
 *
 * Makes the public Terms of Service page editable from the Super Admin panel.
 * Content is stored on `superAdmin.panelSettings.termsOfService` — the same
 * read/merge/write blob the Privacy Policy, 2FA policy and AI config already
 * use — so nothing is hardcoded, nothing needs a redeploy, and no new
 * collection is required.
 *
 * Deliberately a copy of privacyPolicySettings.ts rather than a shared
 * abstraction: the two are independent content slots that happen to look alike
 * today, and the router is thin enough that factoring it out would couple two
 * legal pages for no gain.
 *
 * `GET /content` is deliberately public (no auth): the Terms page is a public
 * marketing page. Until an admin saves content the route answers
 * `{ configured: false }` and the page keeps rendering its existing hardcoded
 * copy, so current visitors are unaffected until the terms are actually updated.
 */

import express, { Request, Response } from 'express';
import { body, validationResult } from 'express-validator';
import { authenticate, requireRole } from '../middleware/auth';
import { getModels } from '../models';

const router = express.Router();

/**
 * The terms shown before an admin has saved anything. A faithful HTML
 * transcription of the hardcoded page the app shipped with, so the editor starts
 * from the live copy and only real edits change what the public sees.
 */
const DEFAULT_TERMS_HTML = `
<h2>1. Acceptance of Terms</h2>
<p>
  By accessing or using the Mengo platform (&quot;Service&quot;), you agree to be bound by these Terms of Service (&quot;Terms&quot;). If you do not agree to these Terms, you may not access or use the Service. These Terms apply to all visitors, users, and others who access or use the Service.
</p>

<h2>2. Description of Service</h2>
<p>
  Mengo is an AI-powered Chief Marketing Officer platform that provides marketing strategy, content generation, brand management, and related tools. The Service includes, but is not limited to, AI-generated marketing content, campaign planning, social media management, brand asset creation, and analytics.
</p>

<h2>3. User Accounts</h2>
<p>
  To use certain features of the Service, you must create an account. You are responsible for safeguarding your account password and for all activities that occur under your account. You agree to notify Mengo immediately of any unauthorized use of your account. You must provide accurate, current, and complete information during registration and keep your account information updated.
</p>

<h2>4. Acceptable Use</h2>
<p>You agree not to use the Service to:</p>
<ul>
  <li>Violate any applicable laws or regulations</li>
  <li>Infringe upon the intellectual property rights of others</li>
  <li>Generate misleading, harmful, or fraudulent content</li>
  <li>Distribute spam, malware, or other harmful materials</li>
  <li>Attempt to gain unauthorized access to any part of the Service</li>
  <li>Use the Service in any way that could damage, disable, or impair its operation</li>
</ul>

<h2>5. AI-Generated Content</h2>
<p>
  The Service uses artificial intelligence to generate marketing content, strategies, and recommendations. You acknowledge that AI-generated content may not always be accurate, complete, or suitable for your specific needs. You are solely responsible for reviewing, editing, and approving any AI-generated content before publishing or distributing it. Mengo does not guarantee the accuracy, quality, or fitness for purpose of AI-generated outputs.
</p>

<h2>6. Intellectual Property</h2>
<p>
  You retain ownership of all content you input into the Service. Content generated by the Service using your input is owned by you, subject to the rights granted in these Terms. You grant Mengo a limited, non-exclusive license to process your input solely for the purpose of providing the Service. Mengo reserves all rights in the Service itself, including its design, branding, and underlying technology.
</p>

<h2>7. Data and Privacy</h2>
<p>
  Your use of the Service is also governed by our <a href="/privacy-policy">Privacy Policy</a>, which describes how we collect, use, and protect your personal information. By using the Service, you consent to the collection and use of your data as described in our Privacy Policy.
</p>

<h2>8. Limitation of Liability</h2>
<p>
  To the maximum extent permitted by law, Mengo shall not be liable for any indirect, incidental, special, consequential, or punitive damages arising out of or relating to your use of the Service. This includes, but is not limited to, damages for loss of profits, data, or other intangible losses. Our total liability shall not exceed the amount you paid for the Service in the twelve months preceding the claim.
</p>

<h2>9. Termination</h2>
<p>
  We may terminate or suspend your account and access to the Service at our sole discretion, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties. Upon termination, your right to use the Service will immediately cease. Provisions that by their nature should survive termination shall remain in effect.
</p>

<h2>10. Changes to Terms</h2>
<p>
  We reserve the right to modify or replace these Terms at any time. If a revision is material, we will provide at least 30 days&apos; notice before the new Terms take effect. What constitutes a material change will be determined at our sole discretion. Your continued use of the Service after any changes constitutes acceptance of the new Terms.
</p>

<h2>11. Contact</h2>
<p>
  If you have any questions about these Terms, please contact us at <a href="mailto:support@mengoengine.com">support@mengoengine.com</a>.
</p>
`;

function rejectInvalid(req: Request, res: Response): boolean {
  const errors = validationResult(req);
  if (errors.isEmpty()) return false;
  res.status(400).json({ error: errors.array()[0]?.msg || 'Invalid request' });
  return true;
}

/**
 * Merge a value into the super-admin's panelSettings — the same read/merge/write
 * the security and privacy policy routers use. A dotted `$set` looks tidy but
 * becomes a literal key under the in-memory mock model, so the merge is done in
 * JS and the whole object written back with markModified.
 */
async function savePanelSetting(key: string, value: any): Promise<boolean> {
  const { User } = getModels();
  const superAdmin = await User.findOne({ role: 'super-admin' });
  if (!superAdmin) return false;

  const current = (superAdmin as any).panelSettings || {};
  (superAdmin as any).panelSettings = { ...current, [key]: value };

  // Mixed fields need an explicit dirty flag under Mongoose; the mock document
  // has no such method, hence the guard.
  if (typeof (superAdmin as any).markModified === 'function') {
    (superAdmin as any).markModified('panelSettings');
  }
  await superAdmin.save();

  return true;
}

/** Read the stored terms blob, or null when never saved. */
async function readStoredTerms(): Promise<any> {
  const { User } = getModels();
  const superAdmin = await User.findOne({ role: 'super-admin' }).select('panelSettings').lean();
  return (superAdmin as any)?.panelSettings?.termsOfService || null;
}

/** GET /content — public. { configured: false } until an admin saves content. */
router.get('/content', async (_req: Request, res: Response) => {
  try {
    const stored = await readStoredTerms();
    const content = typeof stored?.content === 'string' ? stored.content : '';
    if (!content.trim()) {
      res.json({ configured: false });
      return;
    }
    res.json({
      configured: true,
      content,
      updatedAt: stored?.updatedAt || null,
    });
  } catch (error: any) {
    console.error('[Terms] Failed to read public content:', error?.message);
    res.status(500).json({ error: 'Failed to load the terms of service' });
  }
});

/** GET /settings — super-admin only. Returns current content (or the default). */
router.get('/settings', authenticate, requireRole('super-admin'), async (_req: Request, res: Response) => {
  try {
    const stored = await readStoredTerms();
    const content = typeof stored?.content === 'string' && stored.content.trim()
      ? stored.content
      : DEFAULT_TERMS_HTML;
    res.json({
      content,
      configured: Boolean(stored?.content?.trim()),
      updatedAt: stored?.updatedAt || null,
    });
  } catch (error: any) {
    console.error('[Terms] Failed to read settings:', error?.message);
    res.status(500).json({ error: 'Failed to load terms of service settings' });
  }
});

/** PUT /settings — super-admin only. Saves the edited content. */
router.put(
  '/settings',
  authenticate,
  requireRole('super-admin'),
  [body('content').isString().withMessage('Content is required')],
  async (req: Request, res: Response) => {
    if (rejectInvalid(req, res)) return;

    try {
      const saved = await savePanelSetting('termsOfService', {
        content: req.body.content,
        updatedAt: new Date().toISOString(),
        updatedBy: String((req.user as any)?._id || (req.user as any)?.id || ''),
      });

      if (!saved) {
        res.status(404).json({ error: 'Super Admin not found' });
        return;
      }

      res.json({ success: true, content: req.body.content });
    } catch (error: any) {
      console.error('[Terms] Failed to save content:', error?.message);
      res.status(500).json({ error: 'Failed to save the terms of service' });
    }
  },
);

export default router;
