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 toutes les notes de l'utilisateur connecté
 */
export async function GET(request: Request) {
  try {
    const session = await getServerSession(authOptions);

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

    const { searchParams } = new URL(request.url);
    const search = searchParams.get('search');

    let notes;
    if (search) {
      notes = await notesService.searchNotes(session.user.id, search);
    } else {
      notes = await notesService.getNotes(session.user.id);
    }

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

/**
 * API route pour créer une nouvelle note
 */
export async function POST(request: Request) {
  try {
    const session = await getServerSession(authOptions);

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

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

    if (!title || !content) {
      return NextResponse.json(
        { error: 'Title and content are required' },
        { status: 400 }
      );
    }

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

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