import { describe, it, expect } from 'vitest';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';

const CONTENT_DIR = path.join(process.cwd(), 'content/blog');
const LOCALES = ['en', 'pl', 'fr', 'es'];

function getAllPostFiles(): Array<{ locale: string; filename: string; filePath: string }> {
  const posts: Array<{ locale: string; filename: string; filePath: string }> = [];
  for (const locale of LOCALES) {
    const dir = path.join(CONTENT_DIR, locale);
    if (!fs.existsSync(dir)) continue;
    const files = fs.readdirSync(dir).filter((f) => /\.(md|mdx)$/.test(f));
    files.forEach((filename) => {
      posts.push({ locale, filename, filePath: path.join(dir, filename) });
    });
  }
  return posts;
}

describe('Blog post content validation', () => {
  const posts = getAllPostFiles();

  it('should have at least one blog post', () => {
    expect(posts.length).toBeGreaterThanOrEqual(1);
  });

  describe.each(posts)('$locale/$filename', ({ filename, filePath }) => {
    const raw = fs.readFileSync(filePath, 'utf8');
    const { data, content } = matter(raw);

    it('should have a non-empty title', () => {
      expect(data.title).toBeTruthy();
      expect(typeof data.title).toBe('string');
    });

    it('should have a non-empty description', () => {
      expect(data.description).toBeTruthy();
      expect(typeof data.description).toBe('string');
    });

    it('should have a valid date in YYYY-MM-DD format', () => {
      expect(data.date).toBeTruthy();
      expect(data.date).toMatch(/^\d{4}-\d{2}-\d{2}$/);
      const parsed = new Date(data.date);
      expect(parsed.toString()).not.toBe('Invalid Date');
    });

    it('should have non-empty markdown body content', () => {
      expect(content.trim().length).toBeGreaterThan(0);
    });

    it('should have a slug-friendly filename', () => {
      const slug = filename.replace(/\.(md|mdx)$/, '');
      expect(slug).toMatch(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/);
    });

    it('should have readingTime as a positive number if present', () => {
      if (data.readingTime !== undefined) {
        expect(typeof data.readingTime).toBe('number');
        expect(data.readingTime).toBeGreaterThan(0);
      }
    });

    it('should have tags as an array of strings if present', () => {
      if (data.tags !== undefined) {
        expect(Array.isArray(data.tags)).toBe(true);
        data.tags.forEach((tag: unknown) => {
          expect(typeof tag).toBe('string');
          expect((tag as string).trim().length).toBeGreaterThan(0);
        });
      }
    });

    it('should have author as a non-empty string if present', () => {
      if (data.author !== undefined) {
        expect(typeof data.author).toBe('string');
        expect(data.author.trim().length).toBeGreaterThan(0);
      }
    });
  });
});
