'use server';

import { cookies } from 'next/headers';
import { revalidatePath } from 'next/cache';

export async function updateProfile(formData: FormData) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('token')?.value;

    if (!token) {
      return {
        success: false,
        message: 'Authentication required. Please log in.',
      };
    }

    const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';
    
    // Pass FormData directly - the API route will handle the conversion
    const response = await fetch(`${baseUrl}/api/user/profile`, {
      method: 'POST',
      headers: {
        'Cookie': `token=${token}`,
      },
      body: formData,
      cache: 'no-store',
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      return {
        success: false,
        message: errorData.message || `Failed to update profile (${response.status})`,
      };
    }

    const result = await response.json();

    // Revalidate profile-related pages
    revalidatePath('/dashboard/profile');
    revalidatePath('/dashboard');

    return {
      success: true,
      message: 'Profile updated successfully!',
      data: result,
    };
  } catch (error: any) {
    console.error('Profile Update Error:', error);
    return {
      success: false,
      message: error.message || 'Failed to update profile',
    };
  }
}

export async function updateUserRoles(roleIds: number[]) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('token')?.value;

    if (!token) {
      return {
        success: false,
        message: 'Authentication required. Please log in.',
      };
    }

    const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';
    
    const response = await fetch(`${baseUrl}/api/user/update-roles`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Cookie': `token=${token}`,
      },
      body: JSON.stringify({ role_ids: roleIds }),
      cache: 'no-store',
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      return {
        success: false,
        message: errorData.message || `Failed to update roles (${response.status})`,
      };
    }

    const result = await response.json();

    // Revalidate profile-related pages
    revalidatePath('/dashboard/profile');
    revalidatePath('/dashboard');

    return {
      success: true,
      message: 'Roles updated successfully!',
      data: result,
    };
  } catch (error: any) {
    console.error('Roles Update Error:', error);
    return {
      success: false,
      message: error.message || 'Failed to update roles',
    };
  }
}
