import type { Response } from "express";
import type { AuthenticatedRequest } from "../@types/auth.js";
import {
  listClientReviews,
  getClientReviewById,
  createClientReview,
  updateClientReview,
  deleteClientReview,
} from "../services/clientReviewService.js";
import { sendSuccess, sendError } from "../utils/apiResponse.js";

const getStaffId = (req: AuthenticatedRequest): number => {
  if (req.auth?.actorType === "staff") {
    return req.auth.staff.id;
  }
  throw new Error("UNAUTHORIZED");
};

export const listAdminClientReviews = async (
  req: AuthenticatedRequest,
  res: Response,
) => {
  const query = req.validatedQuery as {
    q?: string;
    page: number;
    perPage: number;
    includeInactive?: boolean;
  };

  const result = await listClientReviews(query);
  return sendSuccess(res, 200, result);
};

export const getAdminClientReviewById = async (
  req: AuthenticatedRequest,
  res: Response,
) => {
  const { id } = req.validatedParams as { id: number };

  const review = await getClientReviewById(id);
  if (!review) {
    return sendError(res, 404, "CLIENT_REVIEW_NOT_FOUND", "Client review not found.");
  }

  return sendSuccess(res, 200, review);
};

export const createAdminClientReview = async (
  req: AuthenticatedRequest,
  res: Response,
) => {
  const input = req.validatedBody as Parameters<typeof createClientReview>[0];
  const staffId = getStaffId(req);

  try {
    const review = await createClientReview(input, staffId);
    return sendSuccess(res, 201, review, "Client review created.");
  } catch (error: any) {
    if (error.message === "CLIENT_REVIEW_CREATE_FAILED") {
      return sendError(res, 500, "CLIENT_REVIEW_CREATE_FAILED", "Failed to create client review.");
    }
    throw error;
  }
};

export const updateAdminClientReview = async (
  req: AuthenticatedRequest,
  res: Response,
) => {
  const { id } = req.validatedParams as { id: number };
  const input = req.validatedBody as Parameters<typeof updateClientReview>[1];
  const staffId = getStaffId(req);

  try {
    const review = await updateClientReview(id, input, staffId);
    return sendSuccess(res, 200, review, "Client review updated.");
  } catch (error: any) {
    if (error.message === "CLIENT_REVIEW_NOT_FOUND") {
      return sendError(res, 404, "CLIENT_REVIEW_NOT_FOUND", "Client review not found.");
    }
    throw error;
  }
};

export const deleteAdminClientReview = async (
  req: AuthenticatedRequest,
  res: Response,
) => {
  const { id } = req.validatedParams as { id: number };

  try {
    await deleteClientReview(id);
    return sendSuccess(res, 200, null, "Client review deleted.");
  } catch (error: any) {
    if (error.message === "CLIENT_REVIEW_NOT_FOUND") {
      return sendError(res, 404, "CLIENT_REVIEW_NOT_FOUND", "Client review not found.");
    }
    throw error;
  }
};
