import type { Response } from "express";
import type { AuthenticatedRequest } from "../@types/auth.js";
import { sendError, sendSuccess } from "../utils/apiResponse.js";
import * as bannerService from "../services/bannerService.js";

export const listAdminBanners = async (req: AuthenticatedRequest, res: Response) => {
  const query = req.validatedQuery as bannerService.ListBannersQuery;
  const result = await bannerService.listBanners(query);
  return sendSuccess(res, 200, result);
};

export const getAdminBannerById = async (req: AuthenticatedRequest, res: Response) => {
  const { id } = req.validatedParams as { id: number };
  const banner = await bannerService.getBannerById(id);
  if (!banner) {
    return sendError(res, 404, "BANNER_NOT_FOUND", "Banner not found.");
  }
  return sendSuccess(res, 200, banner);
};

export const createAdminBanner = async (req: AuthenticatedRequest, res: Response) => {
  const input = req.validatedBody as bannerService.CreateBannerInput;
  const banner = await bannerService.createBanner(input);
  return sendSuccess(res, 201, banner, "Banner created.");
};

export const updateAdminBanner = async (req: AuthenticatedRequest, res: Response) => {
  const { id } = req.validatedParams as { id: number };
  const input = req.validatedBody as bannerService.UpdateBannerInput;
  const existing = await bannerService.getBannerById(id);
  if (!existing) {
    return sendError(res, 404, "BANNER_NOT_FOUND", "Banner not found.");
  }
  const banner = await bannerService.updateBanner(id, input);
  return sendSuccess(res, 200, banner, "Banner updated.");
};

export const deleteAdminBanner = async (req: AuthenticatedRequest, res: Response) => {
  const { id } = req.validatedParams as { id: number };
  const existing = await bannerService.getBannerById(id);
  if (!existing) {
    return sendError(res, 404, "BANNER_NOT_FOUND", "Banner not found.");
  }
  await bannerService.deleteBanner(id);
  return sendSuccess(res, 200, null, "Banner deleted.");
};

export const listPublicBanners = async (_req: AuthenticatedRequest, res: Response) => {
  const banners = await bannerService.listActiveBanners();
  return sendSuccess(res, 200, banners);
};
