import {
  createBlogSchema,
  updateBlogSchema,
  normalizeBlogPayload,
} from "../models/blog.schema.js";
import {
  listBlogs,
  getBlogById,
  getBlogByCategory,
  createBlog,
  updateBlog,
  updateBlogByCategory,
  deleteBlog,
  updateComponentByCategory,
  updateHeroSectionByCategory,
} from "../services/blogs.service.js";
import { successResponse, errorResponse } from "../utils/response.js";
import { HTTP_STATUS } from "../constants/index.js";
import logger from "../utils/logger.js";

export const list = async (req, res, next) => {
  try {
    const items = await listBlogs();
    return successResponse(res, items, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error listing blogs:", err);
    next(err);
  }
};

export const getById = async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, "Blog ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    const item = await getBlogById(id);
    if (!item) {
      return errorResponse(res, "Blog not found", HTTP_STATUS.NOT_FOUND);
    }
    return successResponse(res, item, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error getting blog by ID:", err);
    next(err);
  }
};

export const getByCategory = async (req, res, next) => {
  try {
    const { category } = req.params;
    if (!category) {
      return errorResponse(res, "Blog category is required", HTTP_STATUS.BAD_REQUEST);
    }
    const item = await getBlogByCategory(category);
    if (!item) {
      return errorResponse(res, "Blog not found", HTTP_STATUS.NOT_FOUND);
    }
    return successResponse(res, item, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error getting blog by category:", err);
    next(err);
  }
};

export const create = async (req, res, next) => {
  try {
    const normalized = normalizeBlogPayload(req.body);
    const parsed = createBlogSchema.safeParse(normalized);
    if (!parsed.success) {
      return errorResponse(
        res,
        "Validation failed",
        HTTP_STATUS.BAD_REQUEST,
        parsed.error.flatten()
      );
    }
    const created = await createBlog(parsed.data);
    logger.info(`Blog created with ID: ${created.id || created._id}`);
    return successResponse(res, created, HTTP_STATUS.CREATED);
  } catch (err) {
    logger.error("Error creating blog:", err);
    next(err);
  }
};

export const update = async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, "Blog ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    const normalized = normalizeBlogPayload(req.body);
    const parsed = updateBlogSchema.safeParse(normalized);
    if (!parsed.success) {
      return errorResponse(
        res,
        "Validation failed",
        HTTP_STATUS.BAD_REQUEST,
        parsed.error.flatten()
      );
    }
    const updated = await updateBlog(id, parsed.data);
    if (!updated) {
      return errorResponse(res, "Blog not found", HTTP_STATUS.NOT_FOUND);
    }
    logger.info(`Blog updated with ID: ${id}`);
    return successResponse(res, updated, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error updating blog:", err);
    next(err);
  }
};

export const updateByCategory = async (req, res, next) => {
  try {
    const { category } = req.params;
    if (!category) {
      return errorResponse(res, "Blog category is required", HTTP_STATUS.BAD_REQUEST);
    }
    const normalized = normalizeBlogPayload(req.body);
    const parsed = updateBlogSchema.safeParse(normalized);
    if (!parsed.success) {
      return errorResponse(
        res,
        "Validation failed",
        HTTP_STATUS.BAD_REQUEST,
        parsed.error.flatten()
      );
    }
    const updated = await updateBlogByCategory(category, parsed.data);
    logger.info(`Blog updated/created for category: ${category}`);
    return successResponse(res, updated, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error updating blog by category:", err);
    next(err);
  }
};

export const remove = async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, "Blog ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    const ok = await deleteBlog(id);
    if (!ok) {
      return errorResponse(res, "Blog not found", HTTP_STATUS.NOT_FOUND);
    }
    logger.info(`Blog deleted with ID: ${id}`);
    return res.status(HTTP_STATUS.NO_CONTENT).send();
  } catch (err) {
    logger.error("Error deleting blog:", err);
    next(err);
  }
};

export const updateComponent = async (req, res, next) => {
  try {
    const { category, componentId } = req.params;
    if (!category) {
      return errorResponse(res, "Blog category is required", HTTP_STATUS.BAD_REQUEST);
    }
    if (!componentId) {
      return errorResponse(res, "Component ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    
    const componentData = req.body;
    const updated = await updateComponentByCategory(category, componentId, componentData);
    
    if (!updated) {
      return errorResponse(res, "Blog or component not found", HTTP_STATUS.NOT_FOUND);
    }
    
    logger.info(`Component ${componentId} updated for category: ${category}`);
    return successResponse(res, updated, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error updating component:", err);
    if (err.message === "Blog not found" || err.message === "Component not found") {
      return errorResponse(res, err.message, HTTP_STATUS.NOT_FOUND);
    }
    next(err);
  }
};

export const updateHeroSection = async (req, res, next) => {
  try {
    const { category } = req.params;
    if (!category) {
      return errorResponse(res, "Blog category is required", HTTP_STATUS.BAD_REQUEST);
    }
    
    const heroData = req.body;
    const updated = await updateHeroSectionByCategory(category, heroData);
    
    logger.info(`Hero section updated for category: ${category}`);
    return successResponse(res, updated, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error updating hero section:", err);
    next(err);
  }
};

