import type { Response } from "express";
import type { AuthenticatedRequest } from "../@types/auth.js";
import {
  listFrameShapes,
  getFrameShapeById,
  createFrameShape,
  updateFrameShape,
  deleteFrameShape,
} from "../services/frameShapeService.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 listAdminFrameShapes = async (
  req: AuthenticatedRequest,
  res: Response,
) => {
  const query = req.validatedQuery as {
    q?: string;
    page: number;
    perPage: number;
    includeInactive?: boolean;
  };

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

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

  const frameShape = await getFrameShapeById(id);
  if (!frameShape) {
    return sendError(res, 404, "FRAME_SHAPE_NOT_FOUND", "Frame shape not found.");
  }

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

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

  try {
    const frameShape = await createFrameShape(input, staffId);
    return sendSuccess(res, 201, frameShape, "Frame shape created.");
  } catch (error: any) {
    if (error.message === "FRAME_SHAPE_NOT_FOUND") {
      return sendError(res, 404, "FRAME_SHAPE_NOT_FOUND", "Frame shape not found.");
    }
    throw error;
  }
};

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

  try {
    const frameShape = await updateFrameShape(id, input, staffId);
    return sendSuccess(res, 200, frameShape, "Frame shape updated.");
  } catch (error: any) {
    if (error.message === "FRAME_SHAPE_NOT_FOUND") {
      return sendError(res, 404, "FRAME_SHAPE_NOT_FOUND", "Frame shape not found.");
    }
    throw error;
  }
};

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

  try {
    await deleteFrameShape(id);
    return sendSuccess(res, 200, null, "Frame shape deleted.");
  } catch (error: any) {
    if (error.message === "FRAME_SHAPE_NOT_FOUND") {
      return sendError(res, 404, "FRAME_SHAPE_NOT_FOUND", "Frame shape not found.");
    }
    throw error;
  }
};
