import { NextResponse } from 'next/server';
import { tasksService } from '@/services/task-management/tasks';
import { TaskStatus } from '@/lib/types';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';

/**
 * API route pour récupérer les tâches avec filtres optionnels
 */
export async function GET(request: Request) {
  try {
    // Vérifier l'authentification
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, error: 'Non authentifié' },
        { status: 401 }
      );
    }

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

    // Extraire les paramètres de filtre
    const filters: {
      status?: TaskStatus[];
      source?: string[];
      search?: string;
      limit?: number;
      offset?: number;
      ownerId?: string; // Filtre par propriétaire
    } = {};

    const status = searchParams.get('status');
    if (status) {
      filters.status = status.split(',') as TaskStatus[];
    }

    const source = searchParams.get('source');
    if (source) {
      filters.source = source.split(',');
    }

    const search = searchParams.get('search');
    if (search) {
      filters.search = search;
    }

    const limit = searchParams.get('limit');
    if (limit) {
      filters.limit = parseInt(limit);
    }

    const offset = searchParams.get('offset');
    if (offset) {
      filters.offset = parseInt(offset);
    }

    // Récupérer les tâches
    const tasks = await tasksService.getTasks(session.user.id, filters);
    const stats = await tasksService.getTaskStats(session.user.id);

    return NextResponse.json({
      success: true,
      data: tasks,
      stats,
      filters: filters,
      count: tasks.length,
    });
  } catch (error) {
    console.error('❌ Erreur lors de la récupération des tâches:', error);

    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Erreur inconnue',
      },
      { status: 500 }
    );
  }
}

// POST, PATCH, DELETE methods have been migrated to Server Actions
// See /src/actions/tasks.ts for:
// - createTask (replaces POST)
// - updateTask, updateTaskStatus, updateTaskTitle (replaces PATCH)
// - deleteTask (replaces DELETE)
