import "server-only";
import { getDbPool } from "./db";

function getAdminBaseUrl() {
  return (
    process.env.ADMIN_UPLOADS_BASE_URL ||
    process.env.NEXT_PUBLIC_ADMIN_UPLOADS_BASE_URL ||
    "http://127.0.0.1/saqib_brand/admin"
  ).replace(/\/$/, "");
}

function normalizeImageUrl(imagePath) {
  if (!imagePath) {
    return "";
  }

  if (/^https?:\/\//i.test(imagePath)) {
    return imagePath;
  }

  return `${getAdminBaseUrl()}/${imagePath.replace(/^\/+/, "")}`;
}

function formatBlogSummary(row) {
  return {
    id: row.id,
    title: row.title,
    slug: row.slug,
    excerpt: row.excerpt || "",
    featuredImageUrl: normalizeImageUrl(row.featured_image),
    imageAlt: row.image_alt || row.title,
    imageTitle: row.image_title || row.title,
    status: row.status,
    updatedAt: row.updated_at,
  };
}

function formatBlogDetail(row) {
  if (!row) {
    return null;
  }

  return {
    ...formatBlogSummary(row),
    contentHeading: row.content_heading || row.title,
    contentHtml: row.content_html || "",
    metaTitle: row.meta_title || row.title,
    metaDescription: row.meta_description || row.excerpt || "",
    metaKeywords: row.meta_keywords || "",
    createdAt: row.created_at,
  };
}

async function queryBlogs(query, params = []) {
  try {
    const [rows] = await getDbPool().query(query, params);
    return rows;
  } catch (error) {
    if (error?.code === "ER_NO_SUCH_TABLE") {
      return [];
    }

    throw error;
  }
}

export async function getPublishedBlogs() {
  const rows = await queryBlogs(
    `SELECT id, title, slug, excerpt, featured_image, image_alt, image_title, status, updated_at
     FROM blogs
     WHERE status = 'published'
     ORDER BY updated_at DESC, id DESC`
  );

  return rows.map(formatBlogSummary);
}

export async function getPublishedBlogBySlug(slug) {
  const rows = await queryBlogs(
    `SELECT id, title, slug, content_heading, excerpt, content_html, featured_image, image_alt, image_title,
            meta_title, meta_description, meta_keywords, status, created_at, updated_at
     FROM blogs
     WHERE slug = ? AND status = 'published'
     LIMIT 1`,
    [slug]
  );

  return formatBlogDetail(rows[0] || null);
}
