import axiosInstance from '../axiosConfig';
import { logger } from '../debugConfig';
import { supabase } from '../supabaseClient';

export interface ProvisionUserResponse {
  user_db_name: string;
  worker_db_name?: string | null;
  worker_type?: string | null;
}

export interface ProvisionSchoolResponse {
  db_name: string;
  curriculum_db_name: string;
}

export async function provisionUser(userId: string, accessToken?: string | null): Promise<ProvisionUserResponse | null> {
  try {
    let token = accessToken || null;
    if (!token) {
      const { data: sessionData } = await supabase.auth.getSession();
      token = sessionData.session?.access_token || null;
    }
    if (!token) {
      logger.warn('provisioning-service', '⚠️ No access token available for provisioning', { userId });
      return null;
    }

    logger.debug('provisioning-service', '🔄 Provisioning user', {
      userId,
      hasToken: !!token,
      baseURL: axiosInstance.defaults.baseURL
    });

    const { data } = await axiosInstance.post<ProvisionUserResponse>(
      '/provisioning/users',
      { user_id: userId },
      { 
        headers: { Authorization: `Bearer ${token}` },
        timeout: 5000 // 5 second timeout for provisioning requests
      }
    );
    logger.info('provisioning-service', '✅ User provisioned', {
      userId,
      userDbName: data.user_db_name,
      workerDbName: data.worker_db_name
    });
    return data;
  } catch (error) {
    logger.warn('provisioning-service', '⚠️ Failed to provision user', {
      userId,
      error,
    });
    return null;
  }
}

export async function provisionSchool(instituteId: string, accessToken?: string | null): Promise<ProvisionSchoolResponse | null> {
  try {
    let token = accessToken || null;
    if (!token) {
      const { data: sessionData } = await supabase.auth.getSession();
      token = sessionData.session?.access_token || null;
    }
    if (!token) {
      logger.warn('provisioning-service', '⚠️ No access token available for school provisioning', { instituteId });
      return null;
    }

    const { data } = await axiosInstance.post<ProvisionSchoolResponse>(
      '/provisioning/schools',
      { institute_id: instituteId },
      { 
        headers: { Authorization: `Bearer ${token}` },
        timeout: 5000 // 5 second timeout for provisioning requests
      }
    );
    logger.info('provisioning-service', '✅ School provisioned', {
      instituteId,
      dbName: data.db_name,
    });
    return data;
  } catch (error) {
    logger.warn('provisioning-service', '⚠️ Failed to provision school', {
      instituteId,
      error,
    });
    return null;
  }
}
