import axios, { AxiosError } from "axios";

const CLASSWISE_API_URL = process.env.NEXT_PUBLIC_CLASSWISE_API_URL || "https://backend.classwise.youngengineers.org/api/v3";
const CLASSWISE_ACCOUNT_ID = process.env.NEXT_PUBLIC_CLASSWISE_ACCOUNT_ID || "1162885000220795161";
const CLASSWISE_TOKEN = process.env.CLASSWISE_TOKEN || "";

export interface ClasswiseLocation {
  id: string | number;
  name: string;
  location: string;
  city: string | null;
  country: string;
  country_code: string;
  latlng: string;
  total_students: number;
  total_groups: number;
  total_instructors: number;
  location_image?: string;
  status: string;
}

export interface ClasswiseLocationsResponse {
  status: string;
  message: string;
  data: ClasswiseLocation[];
  total: number;
  totalPage: number;
  currentPage: number;
  perPage: number;
}

// Separate axios instance for Classwise API
const classwiseApiClient = axios.create({
  baseURL: CLASSWISE_API_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Authorization": CLASSWISE_TOKEN,
  },
});

export class ClasswiseLocationsService {
  async fetchLocations(accountId?: string): Promise<ClasswiseLocation[]> {
    const startTime = Date.now();
    const resolvedAccountId = accountId || CLASSWISE_ACCOUNT_ID;

    try {
      const response = await classwiseApiClient.get<ClasswiseLocationsResponse>(
        "/get-POS-list",
        {
          params: {
            account_id: resolvedAccountId,
          },
        }
      );

      if (!response.data?.status || response.data.status !== "success") {
        return [];
      }

      if (!Array.isArray(response.data?.data)) {
        return [];
      }

      const elapsed = Date.now() - startTime;

      return response.data.data;
    } catch (error) {
      const elapsed = Date.now() - startTime;
      console.error(
        `[ClasswiseLocationsService] ✗ Failed to fetch locations in ${elapsed}ms:`,
        error instanceof AxiosError ? error.message : error
      );
      return [];
    }
  }
}

export const classwiseLocationsService = new ClasswiseLocationsService();
