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 PUT(request: Request, { params }: { params: { id: string } }) {
  try {
    const { id } = params;
    const updatedTodo = await request.json();
    const todos = readTodos();
    const todoIndex = todos.findIndex((todo: any) => todo.id === parseInt(id));

    if (todoIndex === -1) {
      return NextResponse.json({ message: 'Todo not found' }, { status: 404 });
    }

    todos[todoIndex] = { ...todos[todoIndex], ...updatedTodo };
    writeTodos(todos);
    return NextResponse.json(todos[todoIndex]);
  } catch (error) {
    return NextResponse.json({ message: 'Error updating todo', error }, { status: 500 });
  }
}

export async function DELETE(request: Request, { params }: { params: { id: string } }) {
  try {
    const { id } = params;
    let todos = readTodos();
    const initialLength = todos.length;
    todos = todos.filter((todo: any) => todo.id !== parseInt(id));

    if (todos.length === initialLength) {
      return NextResponse.json({ message: 'Todo not found' }, { status: 404 });
    }

    writeTodos(todos);
    return NextResponse.json({ message: 'Todo deleted' });
  } catch (error) {
    return NextResponse.json({ message: 'Error deleting todo', error }, { status: 500 });
  }
}
