/**
 * controller.ts (feedback)
 * POST /api/feedback     → enviar retroalimentación (auth)
 * GET  /api/feedback/me  → listar mis feedbacks (auth)
 */

import { Response } from "express";
import { AuthRequest } from "../middlewares/auth.middleware.js";
import { CustomError } from "../../domain/errors/custom.error.js";
import { SubmitFeedbackUseCase } from "../../domain/use-cases/feedback/submit-feedback.use-case.js";
import { ListMyFeedbackUseCase } from "../../domain/use-cases/feedback/list-my-feedback.use-case.js";
import { InMemoryFeedbackRepository } from "../../data/repositories/feedback.repository.impl.js";

export class FeedbackController {
  private static repository = new InMemoryFeedbackRepository();

  private submit = new SubmitFeedbackUseCase(FeedbackController.repository);
  private listMine = new ListMyFeedbackUseCase(FeedbackController.repository);

  create = async (req: AuthRequest, res: Response) => {
    try {
      if (!req.user) throw CustomError.unauthorized("User not authenticated");
      const result = await this.submit.execute(req.user.id, req.body);
      res.status(201).json(result);
    } catch (error) {
      this.handleError(error, res);
    }
  };

  myFeedback = async (req: AuthRequest, res: Response) => {
    try {
      if (!req.user) throw CustomError.unauthorized("User not authenticated");
      const result = await this.listMine.execute(req.user.id);
      res.status(200).json(result);
    } catch (error) {
      this.handleError(error, res);
    }
  };

  private handleError(error: unknown, res: Response): void {
    if (error instanceof CustomError) {
      res.status(error.statusCode).json({ error: error.message });
      return;
    }
    if (error instanceof Error) {
      res.status(400).json({ error: error.message });
      return;
    }
    res.status(500).json({ error: "Internal server error" });
  }
}
