import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

interface DocumentMeta {
  id: string;
  slug: string;
  title: string;
  description: string;
  type: 'table' | 'report' | 'mixed';
  createdAt: string;
}

const DOCS_DIR = path.join(process.cwd(), 'src/app/(dashboard)/document');

export function GET() {
  try {
    const entries = fs.readdirSync(DOCS_DIR, { withFileTypes: true });
    const docs: DocumentMeta[] = [];

    for (const entry of entries) {
      if (!entry.isDirectory()) continue;
      if (entry.name.startsWith('[') || entry.name.startsWith('_')) continue;

      const metaPath = path.join(DOCS_DIR, entry.name, 'meta.json');
      const pagePath = path.join(DOCS_DIR, entry.name, 'page.tsx');

      if (!fs.existsSync(pagePath)) continue;

      let meta: Partial<DocumentMeta> = {};
      if (fs.existsSync(metaPath)) {
        try {
          meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8')) as Partial<DocumentMeta>;
        } catch {
          // ignore malformed meta
        }
      }

      docs.push({
        id: entry.name,
        slug: entry.name,
        title: meta.title || entry.name.replace(/-/g, ' '),
        description: meta.description || '',
        type: (meta.type as DocumentMeta['type']) || 'report',
        createdAt: meta.createdAt || fs.statSync(pagePath).mtime.toISOString(),
      });
    }

    docs.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

    return NextResponse.json({ data: docs });
  } catch {
    return NextResponse.json({ data: [] });
  }
}
