// @ts-nocheck
import { Request, Response } from "express";
import prisma from "../DB/db";
import asyncHandler from "../utils/asyncHandler";
import ApiResponse from "../utils/apiResponse";
import ApiError from "../utils/apiError";
import { uploadFileToR2 } from "../utils/r2";

// --- GET: Fetch Heritage Story (Public) ---
export const getHeritageStory = asyncHandler(async (req: Request, res: Response) => {
  // Always fetch the first active record (assuming single section)
  const story = await prisma.heritageStory.findFirst({
    where: { isActive: true },
  });

  // If no data exists yet, return default mock data so frontend doesn't break
  const data = story || {
    tagline: "The Philosophy",
    title: "Celebrating India's Artisanal Legacy",
    description: "Fabindia is more than a brand; it is a bridge between the artisan and the urban consumer.",
    imageUrl: "https://images.unsplash.com/photo-1606293926075-69a00dbfde81",
    buttonText: "Read Our Story",
    buttonLink: "/about",
  };

  return res.status(200).json(new ApiResponse(true,200, "Heritage story fetched successfully",data));
});

// --- UPDATE: Modify Heritage Story (Admin Only) ---
export const updateHeritageStory = asyncHandler(async (req: Request, res: Response) => {
  const { tagline, title, description, buttonText,imageUrl, buttonLink } = req.body;

  // Check if a record exists
  const existingStory = await prisma.heritageStory.findFirst();
  const image =req.file;
  if(!image){
    throw new ApiError(false,400,"image is required")
  }

  const uploadToR2=await uploadFileToR2(image);
  let story;

  if (existingStory) {
    // Update existing
    story = await prisma.heritageStory.update({
      where: { id: existingStory.id },
      data: {
        tagline,
        title,
        description,
        imageUrl,
        buttonText,
        buttonLink,
      },
    });
  } else {
    // Create new if strictly needed (first time setup)
    story = await prisma.heritageStory.create({
      data: {
        tagline: tagline || "The Philosophy",
        title: title || "Celebrating India's Artisanal Legacy",
        description: description || "Default description...",
        imageUrl: uploadToR2.url || "",
        buttonText: buttonText || "Read More",
        buttonLink: buttonLink || "/about",
      },
    });
  }

  return res.status(200).json(new ApiResponse(true,200, "Heritage story updated successfully",story));
});