"use server";
import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import { createProject, deleteProject, updateProject, DEFAULT_PROJECT_ID } from '../../lib/projects.js';

export async function createProjectAction(formData) {
  const mode = String(formData.get('folder_mode') || 'workspace');
  const customPath = String(formData.get('folder_path') || '').trim();
  const folder_path = mode === 'custom' && customPath ? customPath : undefined;
  const p = createProject({
    name: formData.get('name'),
    color: formData.get('color'),
    description: formData.get('description'),
    folder_path,
  });
  redirect(`/projects/${p.slug}`);
}

export async function deleteProjectAction(formData) {
  const id = String(formData.get('project_id') || '').trim();
  if (!id) return;
  if (id === DEFAULT_PROJECT_ID) return;
  try {
    deleteProject(id);
  } catch (err) {
    if (err?.code === 'PROJECT_PROTECTED') return;
    throw err;
  }
  revalidatePath('/projects');
}

export async function updateProjectAction(formData) {
  const id = String(formData.get('project_id') || '').trim();
  if (!id) return;
  const mode = String(formData.get('folder_mode') || 'keep');
  const customPath = String(formData.get('folder_path') || '').trim();
  const fields = {
    name: String(formData.get('name') || '').trim() || undefined,
    color: String(formData.get('color') || '').trim() || undefined,
    description: String(formData.get('description') || '').trim() || undefined,
  };
  if (mode === 'custom' && customPath) fields.folder_path = customPath;
  updateProject(id, fields);
  revalidatePath('/projects');
  revalidatePath(`/projects/${id}`);
}
