import { Router } from 'express';
import prisma from '../lib/prisma.js';
import { compareVersions } from '../utils/semver.js';

const router = Router();

// Public legal document fetch for mobile/web (no auth).
// Keys we expect: "privacy_policy", "terms_of_service" (but admin can manage any key).
// Accepts both hyphen and underscore formats: "privacy-policy" -> "privacy_policy"
router.get('/legal/:key', async (req, res) => {
  try {
    let key = String(req.params.key || '').trim().toLowerCase();
    if (!key) {
      return res.status(400).json({ error: 'Invalid request', message: 'key is required' });
    }

    // Normalize key: convert hyphens to underscores for database lookup
    // Try both formats: first with underscore (standard), then with hyphen
    let doc = await (prisma as any).legalDocument.findUnique({
      where: { key },
    });

    // If not found with original key, try converting hyphens to underscores
    if (!doc && key.includes('-')) {
      const normalizedKey = key.replace(/-/g, '_');
      doc = await (prisma as any).legalDocument.findUnique({
        where: { key: normalizedKey },
      });
    }

    // If still not found, try converting underscores to hyphens
    if (!doc && key.includes('_')) {
      const normalizedKey = key.replace(/_/g, '-');
      doc = await (prisma as any).legalDocument.findUnique({
        where: { key: normalizedKey },
      });
    }

    if (!doc || !doc.isActive) {
      return res.status(404).json({ error: 'Not found', message: 'Document not found' });
    }

    return res.json({
      document: {
        key: doc.key,
        title: doc.title ?? null,
        content: doc.content,
        url: doc.url ?? null,
        updatedAt: doc.updatedAt,
      },
    });
  } catch (error: any) {
    console.error('Legal document fetch error:', error);
    return res.status(500).json({ error: 'Failed to fetch document', message: error.message });
  }
});

router.post('/version-check', async (req, res) => {
  try {
    const { platform, version } = req.body || {};

    if (!platform || !version || typeof version !== 'string') {
      return res.status(400).json({
        error: 'Invalid request',
        message: 'platform and version are required',
      });
    }

    // Normalize platform to enum values: "android" -> "ANDROID", "ios" -> "IOS"
    const normalizedPlatform = String(platform).toUpperCase();
    if (normalizedPlatform !== 'ANDROID' && normalizedPlatform !== 'IOS') {
      return res.status(400).json({
        error: 'Invalid request',
        message: 'platform must be "android" or "ios"',
      });
    }

    const config = await (prisma as any).appVersion.findUnique({
      where: {
          platform: normalizedPlatform,
      },
    });

    if (!config || !config.isActive) {
      // No config means we do not enforce any versioning.
      return res.json({
        status: 'ok',
        latestVersion: version,
        message: 'No version policy configured. App is allowed.',
      });
    }

    const current = version;
    const latest = config.latestVersion as string;
    const minSupported = config.minSupported as string;
    const forceUpdate = Boolean(config.forceUpdate);

    const cmpToMin = compareVersions(current, minSupported);
    const cmpToLatest = compareVersions(current, latest);

    // 1) Below minSupported → force update
    if (cmpToMin < 0) {
      const updateUrl = config.apkUrl || config.storeUrl;
      if (!updateUrl) {
        // If no URL is provided, log error but still return force update
        console.error('Force update required but no APK URL or Store URL provided');
      }
      return res.json({
        status: 'update_required',
        force: true,
        latestVersion: latest,
        apkUrl: config.apkUrl ?? null,
        storeUrl: config.storeUrl ?? null,
        releaseNotes: config.releaseNotes ?? null,
        message: 'This version is no longer supported. Please update to continue.',
      });
    }

    // 2) Below latest and forceUpdate flag on → force update
    if (cmpToLatest < 0 && forceUpdate) {
      const updateUrl = config.apkUrl || config.storeUrl;
      if (!updateUrl) {
        // If no URL is provided, log error but still return force update
        console.error('Force update required but no APK URL or Store URL provided');
      }
      return res.json({
        status: 'update_required',
        force: true,
        latestVersion: latest,
        apkUrl: config.apkUrl ?? null,
        storeUrl: config.storeUrl ?? null,
        releaseNotes: config.releaseNotes ?? null,
        message: 'A critical update is required. Please update to continue.',
      });
    }

    // 3) Below latest but optional update
    if (cmpToLatest < 0) {
      return res.json({
        status: 'update_available',
        force: false,
        latestVersion: latest,
        apkUrl: config.apkUrl ?? null,
        storeUrl: config.storeUrl ?? null,
        releaseNotes: config.releaseNotes ?? null,
        message: 'A new version is available.',
      });
    }

    // 4) Up to date
    return res.json({
      status: 'ok',
      latestVersion: latest,
      message: 'Your app is up to date.',
    });
  } catch (error: any) {
    console.error('Version check error:', error);
    return res.status(500).json({
      error: 'Version check failed',
      message: error.message,
    });
  }
});

export default router;



