"use server";

import { z } from "zod";

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

const CheckVideoGuidePurchaseResponseSchema = z.object({
  isPurchased: z.boolean(),
  videoLink: z.string().nullable(),
});

export type CheckVideoGuidePurchaseResponse = z.infer<
  typeof CheckVideoGuidePurchaseResponseSchema
>;

export async function checkVideoGuidePurchase(
  productKey: string
): Promise<ActionResponse<CheckVideoGuidePurchaseResponse>> {
  try {
    const response = await http.get<CheckVideoGuidePurchaseResponse>(
      API_ROUTES.checkVideoGuidePurchase(productKey),
      {
        cache: "no-store",
        schema: CheckVideoGuidePurchaseResponseSchema,
      }
    );

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