import { Request, Response } from "express";
import Occasion from "../../models/occasion";
import { uploadImage } from "../../service/s3Bucket";

const postOccasion = async (req: Request, res: Response) => {
  const { key, title, autoNote, sortOrder } = req.body;

  if (!key || typeof key !== "string") {
    return res.status(400).json({ message: "key is required" });
  }
  if (!title || typeof title !== "string") {
    return res.status(400).json({ message: "title is required" });
  }

  try {
    const existing = await Occasion.findOne({ key: key.trim() });
    if (existing) {
      return res.status(400).json({ message: "An occasion with this key already exists" });
    }

    let icon = "";
    if (req.file) {
      icon = await uploadImage(
        req.file,
        process.env.AWS_S3_BUCKET_NAME!,
        process.env.AWS_S3_OCCASIONS_FOLDER,
      );
    }

    const occasion = await Occasion.create({
      key: key.trim(),
      title: title.trim(),
      autoNote: autoNote?.trim() || "",
      icon,
      sortOrder: sortOrder ? Number(sortOrder) : 0,
    });

    res.status(201).json(occasion);
  } catch (err) {
    res.status(500).json({ message: "Something went wrong", error: err });
  }
};

export { postOccasion };
