/**
 * Google Ads Auth Routes (Super Admin → Settings)
 *
 * Platform-wide Google Ads API credential management — super-admin only:
 * - GET    /config     → Credential status (masked, never the secrets)
 * - POST   /config     → Save the platform Google Ads API credentials (encrypted) [super admin]
 * - DELETE /config     → Remove the saved credentials [super admin]
 *
 * Follows the same pattern as Pinterest/Twitter/Threads auth routes.
 */

import express, { Request, Response } from 'express';
import { authenticate, requireRole } from '../middleware/auth';
import {
  getCredentialStatus,
  saveGoogleAdsCredentials,
  deleteGoogleAdsCredentials,
} from '../services/googleAds/googleAdsAuth';

const router = express.Router();

// ============================================
// CONFIG — platform-wide Google Ads API credentials
// ============================================

router.get('/config', authenticate, async (_req: Request, res: Response) => {
  try {
    const status = await getCredentialStatus();
    res.json(status);
  } catch (error) {
    console.error('Google Ads config status error:', error);
    res.status(500).json({ error: 'Failed to load Google Ads API settings' });
  }
});

router.post('/config', authenticate, requireRole('super-admin'), async (req: Request, res: Response) => {
  try {
    const userId = req.user!._id.toString();
    const { developerToken, clientId, clientSecret, redirectUrl, managerId } = req.body;
    const result = await saveGoogleAdsCredentials(userId, { developerToken, clientId, clientSecret, redirectUrl, managerId });

    if (!result.success) {
      return res.status(400).json({ error: result.error });
    }

    const status = await getCredentialStatus();
    res.json({ message: 'Google Ads API settings saved', ...status });
  } catch (error) {
    console.error('Google Ads config save error:', error);
    res.status(500).json({ error: 'Failed to save Google Ads API settings' });
  }
});

router.delete('/config', authenticate, requireRole('super-admin'), async (_req: Request, res: Response) => {
  try {
    await deleteGoogleAdsCredentials();
    const status = await getCredentialStatus();
    res.json({ message: 'Google Ads API settings removed', ...status });
  } catch (error) {
    console.error('Google Ads config delete error:', error);
    res.status(500).json({ error: 'Failed to remove Google Ads API settings' });
  }
});

export default router;