import type { Request, Response, NextFunction } from 'express';
import { AskChatService } from './ask-chat-service';

export class AskChatController {
  constructor(private readonly service: AskChatService) {}

  // POST /api/v1/ask-chat
  ask = async (req: Request, res: Response, next: NextFunction) => {
    const startedAt = Date.now();

    try {
      const q = String(req.body?.q ?? req.body?.question ?? '').trim();
      if (!q) return res.status(400).json({ error: 'Missing q' });

      // Prefer fast method if you implemented it; otherwise fallback
      const svc: any = this.service;
      const out =
        typeof svc.askAutoFast === 'function'
          ? await svc.askAutoFast(q)
          : await this.service.askAuto(q);

      if (process.env.DEBUG_AI === '1') {
        return res.json({ ...out, ms: Date.now() - startedAt });
      }

      return res.json(out);
    } catch (err) {
      console.log('[CONTROLLER ERROR]', err);
      next(err);
    }
  };

  // POST /api/v1/ask-chat/reload-index
  reloadIndex = async (_req: Request, res: Response, next: NextFunction) => {
    try {
      if (process.env.ALLOW_INDEX_RELOAD !== '1') {
        return res.status(403).json({ error: 'Index reload disabled' });
      }
      // this.service.loadIndex();
      return res.json({ ok: true });
    } catch (err) {
      next(err);
    }
  };

  // GET /api/v1/health
  health = async (_req: Request, res: Response) => {
    return res.json({ ok: true });
  };
}
