import { Router, Request, Response, NextFunction } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireNonTemp } from '../../middleware/rbac.middleware';
import { env } from '../../config/env';
import { logger } from '../../utils/logger';
import { rocketchatClient } from '../../services/rocketchat.client';
import { rocketchatService } from './rocketchat.service';
import { siteSettingsService } from '../settings/settings.service';

const router = Router();

/** Check if chat is enabled (DB setting wins, env var is fallback for first boot) */
async function isChatEnabled(): Promise<boolean> {
  try {
    const settings = await siteSettingsService.get();
    // DB setting is authoritative; env var is the initial default
    return settings.enableChat;
  } catch {
    return env.ENABLE_CHAT === 'true';
  }
}

// GET /api/rocketchat/status — health check (any authenticated user)
router.get(
  '/status',
  authenticate,
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const enabled = await isChatEnabled();
      const online = enabled ? await rocketchatClient.healthCheck() : false;
      res.json({ online, enabled });
    } catch (err) {
      logger.error('RC status check failed:', err);
      next(err);
    }
  },
);

// GET /api/rocketchat/config — return RC URLs + enabled status
router.get(
  '/config',
  authenticate,
  async (_req: Request, res: Response, _next: NextFunction) => {
    const enabled = await isChatEnabled();
    res.json({
      enabled,
      embedPort: env.ROCKETCHAT_EMBED_PORT,
      subdomain: 'chat',
      domain: env.DOMAIN,
    });
  },
);

// POST /api/rocketchat/auth — get RC session token for current user (SSO)
router.post(
  '/auth',
  authenticate,
  requireNonTemp,
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const enabled = await isChatEnabled();
      if (!enabled) {
        res.status(400).json({ error: 'Chat is not enabled' });
        return;
      }

      const userId = req.user!.id;
      const tokenData = await rocketchatService.getAuthToken(userId);

      res.json({
        authToken: tokenData.authToken,
        rcUserId: tokenData.rcUserId,
      });
    } catch (err) {
      logger.error('RC auth failed:', err);
      next(err);
    }
  },
);

export const rocketchatRouter = router;
