import { NextResponse } from 'next/server';
import { notesService } from '@/services/notes';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

/**
 * API route pour récupérer une note spécifique
 */
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const resolvedParams = await params;
    const note = await notesService.getNoteById(
      resolvedParams.id,
      session.user.id
    );

    if (!note) {
      return NextResponse.json({ error: 'Note not found' }, { status: 404 });
    }

    return NextResponse.json({ note });
  } catch (error) {
    console.error('Error fetching note:', error);
    return NextResponse.json(
      { error: 'Failed to fetch note' },
      { status: 500 }
    );
  }
}

/**
 * API route pour mettre à jour une note
 */
export async function PUT(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const resolvedParams = await params;
    const body = await request.json();
    const { title, content, taskId, folderId, tags } = body;

    const note = await notesService.updateNote(
      resolvedParams.id,
      session.user.id,
      {
        title,
        content,
        taskId,
        folderId,
        tags,
      }
    );

    return NextResponse.json({ note });
  } catch (error) {
    console.error('Error updating note:', error);
    if (
      error instanceof Error &&
      error.message === 'Note not found or access denied'
    ) {
      return NextResponse.json({ error: 'Note not found' }, { status: 404 });
    }
    return NextResponse.json(
      { error: 'Failed to update note' },
      { status: 500 }
    );
  }
}

/**
 * API route pour supprimer une note
 */
export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const resolvedParams = await params;
    await notesService.deleteNote(resolvedParams.id, session.user.id);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error deleting note:', error);
    if (
      error instanceof Error &&
      error.message === 'Note not found or access denied'
    ) {
      return NextResponse.json({ error: 'Note not found' }, { status: 404 });
    }
    return NextResponse.json(
      { error: 'Failed to delete note' },
      { status: 500 }
    );
  }
}
