"use server";

import { classwiseLocationsService, type ClasswiseLocation } from "../services/classwiseLocationsService";
import { extractDomain } from "../utils/domain";

export interface LocationsActionResponse {
  success: boolean;
  data: ClasswiseLocation[];
  message?: string;
}

export async function fetchLocationsAction(accountId?: string): Promise<LocationsActionResponse> {
  try {
    const domain = await extractDomain();
    let resolvedAccountId = accountId;

    if (domain === "web.youngengineers.org" || domain === "preview.youngengineers.org") {
      resolvedAccountId = process.env.NEXT_PUBLIC_CLASSWISE_GLOBAL_ACCOUNT_ID || "1162885000381811255";
    }

    const locations = await classwiseLocationsService.fetchLocations(resolvedAccountId);

    if (locations.length === 0) {
      return {
        success: false,
        data: [],
        message: "No locations found",
      };
    }


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