"use server";

import { Plan } from "@/components/planes/types";

export type GetPlansResult = {
  data: Plan[];
  error: string | null;
};

export const getPlans = async (): Promise<GetPlansResult> => {
  try {
    const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}planes`, {
      cache: "no-store",
    });

    const error = `Hubo un error al cargar los planes. Vuelva a intentarlo más tarde.`;

    if (!res.ok) {
      return {
        data: [],
        error,
      };
    }

    const data: Plan[] = await res.json();
    if (data.length === 0) throw new Error(error);

    return {
      data,
      error: null,
    };
  } catch (error) {
    return {
      data: [],
      error: error instanceof Error ? error.message : "Unknown error",
    };
  }
};
