/**
 * submit-feedback.dto.ts
 * DTO para enviar retroalimentación sobre el servicio.
 */

export type FeedbackType =
  | "TRUCK_DID_NOT_PASS"
  | "RATING"
  | "SUGGESTION"
  | "OTHER";

export interface SubmitFeedbackDto {
  type: FeedbackType;
  message: string;
  rating?: number; // 1-5, sólo cuando type === "RATING"
}

const VALID_TYPES: FeedbackType[] = [
  "TRUCK_DID_NOT_PASS",
  "RATING",
  "SUGGESTION",
  "OTHER",
];

export class SubmitFeedbackDtoValidator {
  static validate(data: unknown): SubmitFeedbackDto {
    if (typeof data !== "object" || data === null) {
      throw new Error("Invalid feedback payload");
    }

    const obj = data as Record<string, unknown>;

    if (
      typeof obj.type !== "string" ||
      !VALID_TYPES.includes(obj.type as FeedbackType)
    ) {
      throw new Error(`type must be one of: ${VALID_TYPES.join(", ")}`);
    }

    if (typeof obj.message !== "string" || obj.message.trim().length === 0) {
      throw new Error("message is required");
    }

    let rating: number | undefined;
    if (obj.rating !== undefined) {
      if (
        typeof obj.rating !== "number" ||
        obj.rating < 1 ||
        obj.rating > 5
      ) {
        throw new Error("rating must be between 1 and 5");
      }
      rating = obj.rating;
    }

    const result: SubmitFeedbackDto = {
      type: obj.type as FeedbackType,
      message: obj.message.trim(),
    };
    if (rating !== undefined) result.rating = rating;
    return result;
  }
}
