'use server';
import { safeFetchApi } from '@/lib/fetch.api';
import { SurveyAnswerMutate, Survey, SurveyResponse, surveysApiResponseSchema, suveryApiMutationResponseSchema, suveryResponseDeleteSchema, surveysApiResponseForUserSchema } from '../schemas/survey';
import { auth } from '@/lib/auth';



const transformSurvey = (survey: any) => {

  return survey.map((survey: any) => {
    return {
      ...survey,
      published: survey.published ? 'Publicada': 'Borrador',
    }
  })
};


export const getSurveysAction = async (params: {
  page?: number;
  limit?: number;
  search?: string;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}) => {

  const searchParams = new URLSearchParams({
    page: (params.page || 1).toString(),
    limit: (params.limit || 10).toString(),
    ...(params.search && { search: params.search  }),
    ...(params.sortBy && { sortBy: params.sortBy }),
    ...(params.sortOrder && { sortOrder: params.sortOrder }),
  });

  const [error, response] = await safeFetchApi(
    surveysApiResponseSchema,
    `/surveys?${searchParams}`,
    'GET',
  );

  if (error) {
    console.error('Error:', error);
    throw new Error(error.message);
  }


const transformedData = response?.data ? transformSurvey(response?.data) : undefined;

  return {
    data: transformedData,
    meta: response?.meta || {
      page: 1,
      limit: 10,
      totalCount: 0,
      totalPages: 1,
      hasNextPage: false,
      hasPreviousPage: false,
      nextPage: null,
      previousPage: null,
    },
  };
};


export const getSurveysForUserAction = async (params: {
  page?: number;
  limit?: number;
  search?: string;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}) => {
  const session = await auth()
  const searchParams = new URLSearchParams({
    page: (params.page || 1).toString(),
    limit: (params.limit || 10).toString(),
    ...(params.search && { search: params.search  }),
    ...(params.sortBy && { sortBy: params.sortBy }),
    ...(params.sortOrder && { sortOrder: params.sortOrder }),
  });
  const rol = { 
    rol: session?.user.role 
  }
  const [error, response] = await safeFetchApi(
    surveysApiResponseForUserSchema,
    `/surveys/for-user?${searchParams}`,
    'POST',
    rol
  );

  if (error) {
    console.error('Error:', error);
    throw new Error(error.message);
  }


const transformedData = response?.data ? transformSurvey(response?.data) : undefined;

  return {
    data: transformedData,
    meta: response?.meta || {
      page: 1,
      limit: 10,
      totalCount: 0,
      totalPages: 1,
      hasNextPage: false,
      hasPreviousPage: false,
      nextPage: null,
      previousPage: null,
    },
  };
};

export const createSurveyAction = async (payload: Survey) => {
  const { id, ...payloadWithoutId } = payload;
  
  const [error, data] = await safeFetchApi(
    suveryApiMutationResponseSchema,
    '/surveys',
    'POST',
    payloadWithoutId,
  );

  if (error) {
    if (error.message === 'Survey already exists') {
      throw new Error('Ya existe una encuesta con ese titulo');
    }
    // console.error('Error:', error);
    throw new Error('Error al crear la encuesta');
  }

  return data;
};

export const updateSurveyAction = async (payload: Survey) => {
  const { id, ...payloadWithoutId } = payload;

  
  const [error, data] = await safeFetchApi(
    suveryApiMutationResponseSchema,
    `/surveys/${id}`,
    'PATCH',
    payloadWithoutId,
  );

  if (error) {
    if (error.message === 'Survey already exists') {
      throw new Error('Ya existe otra encuesta con ese titulo');
    }
    if (error.message === 'Survey not found') {
      throw new Error('No se encontró la encuesta');
    }
    // console.error('Error:', error);
    // throw new Error(error.message);
    throw new Error('Error al actualizar la encuesta');
  }

  return data;
};

export const deleteSurveyAction = async (id: number) => {
  const [error, data] = await safeFetchApi(
    suveryResponseDeleteSchema,
    `/surveys/${id}`,
    'DELETE',
  );

  if (error) {
    console.error('Error:', error);
    throw new Error(error.message);
  }

  return data;
};

export const getSurveyByIdAction = async (id: number) => {
  const [error, data] = await safeFetchApi(
    suveryApiMutationResponseSchema,
    `/surveys/${id}`,
    'GET',
  );

  if (error) {
    console.error('❌ Error en la API:', error);
    throw new Error(error.message);
  }

  return data;
};

export const saveSurveysAction = async (payload: Survey) => {
  try {
    if (payload.id) {
      return await updateSurveyAction(payload);
    } else {
      return await createSurveyAction(payload);
    }
  } catch (error: any) {
    throw new Error(error.message || 'Error saving account surveys');
  }
};

export const saveSurveyAnswer = async (payload: SurveyResponse) => {  
  const [error, data] = await safeFetchApi(
    SurveyAnswerMutate,
    '/surveys/answers',
    'POST',
    payload,
  )

  if (error) {
    console.error('Error:', error);
    throw new Error(error.message);
  }

  return data;
}