import { Response } from "express";
import AppContentModel from "../../models/AppContentModel";
import ResponseUtil from "../../utils/Response/responseUtils";
import { STATUS_CODES } from "../../constants/statusCodes";
import { CustomRequest } from "../../interfaces/auth";
import { appContentUpsertSchema } from "../../validators/adminValidators";

export const listContentAdmin = async (req: CustomRequest, res: Response) => {
  try {
    const items = await AppContentModel.find().sort({ section: 1 }).lean();
    return ResponseUtil.successResponse(
      res,
      STATUS_CODES.SUCCESS,
      { items },
      "App content sections"
    );
  } catch (e) {
    ResponseUtil.handleError(res, e);
  }
};

export const upsertContentAdmin = async (req: CustomRequest, res: Response) => {
  try {
    const body = await appContentUpsertSchema.parseAsync(req.body);
    const item = await AppContentModel.findOneAndUpdate(
      { section: body.section },
      {
        section: body.section,
        title: body.title ?? "",
        body: body.body,
        metadata: body.metadata ?? {},
      },
      { new: true, upsert: true }
    ).lean();
    return ResponseUtil.successResponse(
      res,
      STATUS_CODES.SUCCESS,
      { item },
      "Content saved"
    );
  } catch (e) {
    ResponseUtil.handleError(res, e);
  }
};

export const getPublicContent = async (req: CustomRequest, res: Response) => {
  try {
    const { section } = req.params;
    const allowed = [
      "privacy_policy",
      "terms",
      "about",
      "help",
      "social_links",
    ];
    if (!allowed.includes(section)) {
      return ResponseUtil.errorResponse(
        res,
        STATUS_CODES.BAD_REQUEST,
        "Invalid section"
      );
    }
    const item = await AppContentModel.findOne({
      section: section as typeof allowed[number],
    }).lean();
    if (!item) {
      return ResponseUtil.errorResponse(
        res,
        STATUS_CODES.NOT_FOUND,
        "Content not configured"
      );
    }
    return ResponseUtil.successResponse(
      res,
      STATUS_CODES.SUCCESS,
      { item },
      "OK"
    );
  } catch (e) {
    ResponseUtil.handleError(res, e);
  }
};
