"use server";

import { classwisePaymentPlansService, type PaymentPlan } from "../services/classwiseClassesService";
import { extractDomain } from "../utils/domain";
import { resolveClasswiseAccountId } from "../utils/resolveClasswiseAccountId";

export interface PaymentPlansActionResponse {
  success: boolean;
  data: PaymentPlan[];
  message?: string;
}

export async function fetchPaymentPlansAction(
  groupId: string | number,
  accountId: string,
  franchiseeId?: string | null,
  franchise?: { zoho_franchise_id?: string | null; zoho_account_link?: string | null } | null
): Promise<PaymentPlansActionResponse> {
  try {
    const domain = await extractDomain();
    const resolvedAccountId = resolveClasswiseAccountId({
      tenantZohoId: accountId,
      franchise,
      domain,
    });

    if (!resolvedAccountId) {
      return {
        success: false,
        data: [],
        message: "Classwise account id is not configured for this franchise",
      };
    }

    const plans = await classwisePaymentPlansService.fetchPaymentPlans(
      groupId,
      resolvedAccountId,
      franchiseeId
    );

    if (plans.length === 0) {
      return {
        success: false,
        data: [],
        message: "No payment plans found for this class",
      };
    }


    return {
      success: true,
      data: plans,
      message: "Payment plans fetched successfully",
    };
  } catch (error) {
    console.error("[fetchPaymentPlansAction] Error:", error);
    return {
      success: false,
      data: [],
      message: error instanceof Error ? error.message : "Failed to fetch payment plans",
    };
  }
}
