import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const postsFile = path.resolve(__dirname, "../../data/blog-posts.json");

function toSlug(value) {
  return value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, "")
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-");
}

async function readPosts() {
  const raw = await fs.readFile(postsFile, "utf8");
  return JSON.parse(raw);
}

async function writePosts(posts) {
  await fs.writeFile(postsFile, JSON.stringify(posts, null, 2));
}

export async function listPosts() {
  const posts = await readPosts();
  return posts.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
}

export async function getPostBySlug(slug) {
  const posts = await readPosts();
  return posts.find((post) => post.slug === slug) || null;
}

export async function createPost(input) {
  const title = input?.title?.trim();
  const content = input?.content?.trim();
  const author = input?.author?.trim() || "ColdBrewNLP";
  const excerpt = input?.excerpt?.trim() || (content ? `${content.slice(0, 150)}${content.length > 150 ? "..." : ""}` : "");

  if (!title || !content) {
    return { status: 400, body: { error: "Title and content are required." } };
  }

  const posts = await readPosts();
  const baseSlug = toSlug(title);
  let slug = baseSlug;
  let counter = 1;

  while (posts.some((post) => post.slug === slug)) {
    counter += 1;
    slug = `${baseSlug}-${counter}`;
  }

  const post = {
    id: slug,
    slug,
    title,
    excerpt,
    content,
    author,
    createdAt: new Date().toISOString(),
  };

  posts.push(post);
  await writePosts(posts);

  return { status: 201, body: post };
}
