/**
 * Google Business Profile Configuration Routes (Super Admin → Settings)
 *
 * Platform-wide Google Business Profile OAuth credential management:
 *   - GET    /        → Get current config (Client Secret masked)
 *   - POST   /        → Save/update Client ID, Client Secret, Redirect URI
 *   - DELETE /        → Remove config (disables DB-based credentials)
 *   - POST   /test    → Test connection with current credentials
 *   - POST   /toggle  → Enable/disable the integration
 *
 * All endpoints require super-admin or admin authentication.
 * Credentials are AES-256-GCM encrypted at rest and never echoed back in full.
 *
 * Mounted at /api/google-business-profile/config — so the router paths
 * are relative (no /config prefix to avoid /config/config doubling).
 */

import express, { Request, Response } from 'express';
import { authenticate } from '../middleware/auth';
import {
  getGoogleBusinessProfileConfig,
  saveGoogleBusinessProfileConfig,
  deleteGoogleBusinessProfileConfig,
  testGoogleBusinessProfileConnection,
  toggleGoogleBusinessProfileEnabled,
} from '../services/googleBusinessProfile/GoogleBusinessProfileConfigService';

const router = express.Router();

// ============================================
// GET CONFIG — Returns masked credentials (safe for frontend)
// ============================================

router.get('/', authenticate, async (req: Request, res: Response) => {
  try {
    if (req.user!.role !== 'super-admin' && req.user!.role !== 'admin') {
      return res.status(403).json({ error: 'Access denied' });
    }

    const config = await getGoogleBusinessProfileConfig();
    res.json({ data: config });
  } catch (error) {
    console.error('[GoogleBusinessProfileConfig] GET / error:', error);
    res.status(500).json({ error: 'Failed to get Google Business Profile configuration' });
  }
});

// ============================================
// SAVE CONFIG — Encrypts Client Secret and stores in DB
// ============================================

router.post('/', authenticate, async (req: Request, res: Response) => {
  try {
    if (req.user!.role !== 'super-admin' && req.user!.role !== 'admin') {
      return res.status(403).json({ error: 'Access denied' });
    }

    const { clientId, clientSecret, redirectUri, enabled } = req.body;

    if (!clientId?.trim()) {
      return res.status(400).json({ error: 'Client ID is required' });
    }
    if (!clientSecret?.trim()) {
      return res.status(400).json({ error: 'Client Secret is required' });
    }
    if (!redirectUri?.trim()) {
      return res.status(400).json({ error: 'Redirect URI is required' });
    }

    const result = await saveGoogleBusinessProfileConfig({
      clientId: clientId.trim(),
      clientSecret: clientSecret.trim(),
      redirectUri: redirectUri.trim(),
      enabled: enabled !== undefined ? enabled : true,
      updatedBy: req.user!._id.toString(),
    });

    if (result.success) {
      const config = await getGoogleBusinessProfileConfig();
      res.json({ data: config });
    } else {
      res.status(500).json({ error: result.error || 'Failed to save configuration' });
    }
  } catch (error) {
    console.error('[GoogleBusinessProfileConfig] POST / error:', error);
    res.status(500).json({ error: 'Failed to save Google Business Profile configuration' });
  }
});

// ============================================
// DELETE CONFIG — Removes DB-stored credentials
// ============================================

router.delete('/', authenticate, async (req: Request, res: Response) => {
  try {
    if (req.user!.role !== 'super-admin' && req.user!.role !== 'admin') {
      return res.status(403).json({ error: 'Access denied' });
    }

    const result = await deleteGoogleBusinessProfileConfig();

    if (result.success) {
      res.json({ data: { message: 'Google Business Profile configuration removed' } });
    } else {
      res.status(500).json({ error: result.error || 'Failed to delete configuration' });
    }
  } catch (error) {
    console.error('[GoogleBusinessProfileConfig] DELETE / error:', error);
    res.status(500).json({ error: 'Failed to delete Google Business Profile configuration' });
  }
});

// ============================================
// TEST CONNECTION — Validates stored credentials
// ============================================

router.post('/test', authenticate, async (req: Request, res: Response) => {
  try {
    if (req.user!.role !== 'super-admin' && req.user!.role !== 'admin') {
      return res.status(403).json({ error: 'Access denied' });
    }

    const result = await testGoogleBusinessProfileConnection();
    res.json({ data: result });
  } catch (error) {
    console.error('[GoogleBusinessProfileConfig] POST /test error:', error);
    res.status(500).json({ error: 'Failed to test connection' });
  }
});

// ============================================
// TOGGLE ENABLED — Enable/disable the integration
// After toggling, re-fetches the full config so the frontend
// gets a complete config object (not just { success, enabled }).
// ============================================

router.post('/toggle', authenticate, async (req: Request, res: Response) => {
  try {
    if (req.user!.role !== 'super-admin' && req.user!.role !== 'admin') {
      return res.status(403).json({ error: 'Access denied' });
    }

    const { enabled } = req.body;
    if (typeof enabled !== 'boolean') {
      return res.status(400).json({ error: 'enabled must be a boolean' });
    }

    const result = await toggleGoogleBusinessProfileEnabled(enabled);

    if (result.success) {
      // Re-fetch the full config so the frontend gets a complete state
      const config = await getGoogleBusinessProfileConfig();
      res.json({ data: config });
    } else {
      res.status(500).json({ error: result.error || 'Failed to toggle integration' });
    }
  } catch (error) {
    console.error('[GoogleBusinessProfileConfig] POST /toggle error:', error);
    res.status(500).json({ error: 'Failed to toggle integration' });
  }
});

export default router;