'use server';

import { tagsService } from '@/services/task-management/tags';
import { revalidatePath } from 'next/cache';
import { Tag } from '@/lib/types';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';

export type ActionResult<T = void> = {
  success: boolean;
  data?: T;
  error?: string;
};

/**
 * Créer un nouveau tag
 */
export async function createTag(
  name: string,
  color: string
): Promise<ActionResult<Tag>> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'User not authenticated' };
    }

    const tag = await tagsService.createTag({
      name,
      color,
      userId: session.user.id,
    });

    // Revalider les pages qui utilisent les tags
    revalidatePath('/');
    revalidatePath('/kanban');
    revalidatePath('/tags');

    return { success: true, data: tag };
  } catch (error) {
    console.error('Error creating tag:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to create tag',
    };
  }
}

/**
 * Mettre à jour un tag existant
 */
export async function updateTag(
  tagId: string,
  data: { name?: string; color?: string; isPinned?: boolean }
): Promise<ActionResult<Tag>> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'User not authenticated' };
    }

    const tag = await tagsService.updateTag(tagId, session.user.id, data);

    if (!tag) {
      return { success: false, error: 'Tag non trouvé' };
    }

    // Revalider les pages qui utilisent les tags
    revalidatePath('/');
    revalidatePath('/kanban');
    revalidatePath('/tags');

    return { success: true, data: tag };
  } catch (error) {
    console.error('Error updating tag:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to update tag',
    };
  }
}

/**
 * Supprimer un tag
 */
export async function deleteTag(tagId: string): Promise<ActionResult> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'User not authenticated' };
    }

    await tagsService.deleteTag(tagId, session.user.id);

    // Revalider les pages qui utilisent les tags
    revalidatePath('/');
    revalidatePath('/kanban');
    revalidatePath('/tags');

    return { success: true };
  } catch (error) {
    console.error('Error deleting tag:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to delete tag',
    };
  }
}
