import type { Response } from "express";
import type { AuthenticatedRequest } from "../@types/auth.js";
import {
  listBrands,
  getBrandById,
  createBrand,
  updateBrand,
  deleteBrand,
} from "../services/brandService.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 listAdminBrands = async (
  req: AuthenticatedRequest,
  res: Response,
) => {
  const query = req.validatedQuery as {
    q?: string;
    page: number;
    perPage: number;
    includeInactive?: boolean;
  };

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

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

  const brand = await getBrandById(id);
  if (!brand) {
    return sendError(res, 404, "BRAND_NOT_FOUND", "Brand not found.");
  }

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

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

  try {
    const brand = await createBrand(input, staffId);
    return sendSuccess(res, 201, brand, "Brand created.");
  } catch (error: any) {
    if (error.message === "BRAND_NOT_FOUND") {
      return sendError(res, 404, "BRAND_NOT_FOUND", "Brand not found.");
    }
    throw error;
  }
};

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

  try {
    const brand = await updateBrand(id, input, staffId);
    return sendSuccess(res, 200, brand, "Brand updated.");
  } catch (error: any) {
    if (error.message === "BRAND_NOT_FOUND") {
      return sendError(res, 404, "BRAND_NOT_FOUND", "Brand not found.");
    }
    throw error;
  }
};

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

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