import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";

const STORAGE_DIR = path.join(process.cwd(), "data");
const CHANGELOG_FILE = path.join(STORAGE_DIR, "changelog.json");

function ensureDir() {
  if (!fs.existsSync(STORAGE_DIR)) {
    fs.mkdirSync(STORAGE_DIR, { recursive: true });
  }
}

function readJSON(file: string, defaultValue: any = []) {
  ensureDir();
  if (!fs.existsSync(file)) {
    fs.writeFileSync(file, JSON.stringify(defaultValue));
    return defaultValue;
  }
  try {
    return JSON.parse(fs.readFileSync(file, "utf-8"));
  } catch {
    return defaultValue;
  }
}

function writeJSON(file: string, data: any) {
  ensureDir();
  fs.writeFileSync(file, JSON.stringify(data, null, 2));
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const agent = searchParams.get("agent");
  const type = searchParams.get("type");
  const limit = parseInt(searchParams.get("limit") || "50");
  
  let changelog = readJSON(CHANGELOG_FILE, []);
  
  if (agent) {
    changelog = changelog.filter((c: any) => c.agent === agent);
  }
  
  if (type) {
    changelog = changelog.filter((c: any) => c.type === type);
  }
  
  changelog = changelog.slice(0, limit);
  
  return NextResponse.json(changelog);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, entry, entryId } = body;
    
    const changelog = readJSON(CHANGELOG_FILE, []);
    
    if (action === "add") {
      const newEntry = {
        id: `changelog-${Date.now()}`,
        date: new Date().toISOString(),
        ...entry
      };
      changelog.unshift(newEntry);
      writeJSON(CHANGELOG_FILE, changelog);
      return NextResponse.json({ success: true, changelog });
    }
    
    if (action === "delete") {
      const filtered = changelog.filter((c: any) => c.id !== entryId);
      writeJSON(CHANGELOG_FILE, filtered);
      return NextResponse.json({ success: true, changelog: filtered });
    }
    
    return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    
  } catch (error) {
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
