import { Request, Response } from "express";
import { Role } from "@prisma/client";
import { AuthenticatedRequest } from "../../middleware/auth";
import { searchService } from "./search.service";
import { handleError } from "../../utils/http";

export class SearchController {
  async quick(req: Request, res: Response) {
    try {
      const q = String(req.query.q || "").trim();
      const limit = parseInt(String(req.query.limit ?? "8"), 10) || 8;

      const requesterRole = (req as AuthenticatedRequest).user?.role as Role | undefined;
      const requesterId = (req as AuthenticatedRequest).user?.userId as string | undefined;

      const result = await searchService.quickSearch(q, limit, requesterRole, requesterId);
      res.json(result);
    } catch (err: any) {
      return handleError(res, "Search failed", err);
    }
  }

  async full(req: Request, res: Response) {
    try {
      const q = String(req.query.q || "").trim();
      const page = Math.max(parseInt(String(req.query.page ?? "1"), 10) || 1, 1);
      const limit = parseInt(String(req.query.limit ?? "25"), 10) || 25;

      const requesterRole = (req as AuthenticatedRequest).user?.role as Role | undefined;
      const requesterId = (req as AuthenticatedRequest).user?.userId as string | undefined;

      const result = await searchService.fullSearch(q, page, limit, requesterRole, requesterId);
      res.json(result);
    } catch (err: any) {
      return handleError(res, "Search failed", err);
    }
  }
}

export const searchController = new SearchController();
