"use server";

import { revalidateTag } from "next/cache";

import { http } from "@/shared/api/httpClient";
import { API_ROUTES } from "@/shared/constants/api-routes";
import { ActionResponse } from "@/types";

import {
  UserSubscriptionActionPayload,
  UserSubscriptionActionResponse,
  UserSubscriptionActionResponseSchema,
} from "./types";

export async function performUserSubscriptionAction(
  payload: UserSubscriptionActionPayload
): Promise<ActionResponse<UserSubscriptionActionResponse>> {
  try {
    const response = await http.post<UserSubscriptionActionResponse>(
      API_ROUTES.userSubscriptionAction(payload.subscriptionId, payload.action),
      payload,
      {
        schema: UserSubscriptionActionResponseSchema,
        revalidate: 0,
      }
    );

    // Invalidate subscriptions cache to refresh the data
    revalidateTag("subscriptions");

    return { data: response, error: null };
  } catch (error) {
    // eslint-disable-next-line no-console
    console.error("Failed to perform user subscription action:", error);
    const errorMessage =
      error instanceof Error ? error.message : "Something went wrong.";
    return { data: null, error: errorMessage };
  }
}
