import type { Response } from "express";
import type { AuthenticatedRequest } from "../@types/auth.js";
import {
  createProductType,
  deleteProductType,
  getProductTypeById,
  listProductTypes,
  updateProductType,
} from "../services/productTypeService.js";
import { sendError, sendSuccess } 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 listAdminProductTypes = async (
  req: AuthenticatedRequest,
  res: Response,
) => {
  const query = req.validatedQuery as {
    q?: string;
    page: number;
    perPage: number;
    includeInactive?: boolean;
  };

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

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

  const productType = await getProductTypeById(id);
  if (!productType) {
    return sendError(res, 404, "PRODUCT_TYPE_NOT_FOUND", "Product type not found.");
  }

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

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

  try {
    const productType = await createProductType(input, staffId);
    return sendSuccess(res, 201, productType, "Product type created.");
  } catch (error: any) {
    if (error.message === "PRODUCT_TYPE_NOT_FOUND") {
      return sendError(res, 404, "PRODUCT_TYPE_NOT_FOUND", "Product type not found.");
    }
    throw error;
  }
};

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

  try {
    const productType = await updateProductType(id, input, staffId);
    return sendSuccess(res, 200, productType, "Product type updated.");
  } catch (error: any) {
    if (error.message === "PRODUCT_TYPE_NOT_FOUND") {
      return sendError(res, 404, "PRODUCT_TYPE_NOT_FOUND", "Product type not found.");
    }
    throw error;
  }
};

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

  try {
    await deleteProductType(id);
    return sendSuccess(res, 200, null, "Product type deleted.");
  } catch (error: any) {
    if (error.message === "PRODUCT_TYPE_NOT_FOUND") {
      return sendError(res, 404, "PRODUCT_TYPE_NOT_FOUND", "Product type not found.");
    }
    throw error;
  }
};
