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

const todosFilePath = path.join(process.cwd(), 'data', 'todos.json');

function readTodos() {
  const data = fs.readFileSync(todosFilePath, 'utf-8');
  return JSON.parse(data);
}

function writeTodos(todos: any[]) {
  fs.writeFileSync(todosFilePath, JSON.stringify(todos, null, 2), 'utf-8');
}

export async function GET() {
  try {
    const todos = readTodos();
    return NextResponse.json(todos);
  } catch (error) {
    return NextResponse.json({ message: 'Error reading todos', error }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const newTodo = await request.json();
    const todos = readTodos();
    todos.push({ id: Date.now(), ...newTodo });
    writeTodos(todos);
    return NextResponse.json(newTodo, { status: 201 });
  } catch (error) {
    return NextResponse.json({ message: 'Error adding todo', error }, { status: 500 });
  }
}
