import { apiClient } from './apiClient';
import { authApi } from './auth';
import type { LoginResponse } from './types';

/**
 * Hospital-specific API module.
 * Wraps auth endpoints with hospital-context logic.
 */
export const hospitalApi = {
  /**
   * Authenticate a hospital user via the real auth API.
   */
  login: async (username: string, password: string): Promise<LoginResponse> => {
    return authApi.login(username, password);
  },

  /**
   * Verify MFA for hospital user.
   */
  verifyMfa: async (mfaSessionToken: string, totpCode: string): Promise<LoginResponse> => {
    return authApi.verifyMfa(mfaSessionToken, totpCode);
  },

  /**
   * Get hospital profile data from the authenticated user metadata.
   */
  getProfile: async (token: string) => {
    return apiClient.get('/v1/hospital/ops/profile', { token });
  },

  /**
   * Get departments scoped to a specific hospital.
   */
  getDepartments: async (token: string, hospitalId?: string) => {
    const endpoint = hospitalId
      ? `/v1/hospital/departments?hospitalId=${hospitalId}`
      : '/v1/hospital/departments';
    return apiClient.get(endpoint, { token });
  },

  /**
   * Get staff members scoped to a specific hospital.
   */
  getStaff: async (token: string, hospitalId?: string) => {
    const res = await authApi.getUsers(token);
    if (res?.data && hospitalId) {
      const filtered = (Array.isArray(res.data) ? res.data : []).filter(
        (u: any) => u.hospitalId === hospitalId || u.organisationId === hospitalId
      );
      return { ...res, data: filtered };
    }
    return res;
  },

  /**
   * Create a new department under a hospital.
   */
  createDepartment: async (deptData: any, token: string) => {
    return authApi.createDepartment(deptData, token);
  },

  /**
   * Register a staff member under a hospital.
   */
  registerStaff: async (staffData: any, token: string) => {
    return authApi.registerUser(staffData, token);
  },

  updateProfile: async (payload: any, token: string) => {
    return apiClient.patch('/v1/hospital/ops/profile', payload, { token });
  },

  /**
   * Get incoming operations/dispatches for the hospital.
   */
  getIncomingOperations: async (token: string, hospitalId?: string) => {
    const url = hospitalId 
      ? `/v1/hospital/ops/incoming?hospitalId=${hospitalId}`
      : '/v1/hospital/ops/incoming';
    return apiClient.get(url, { token });
  },

  admitPatient: async (patientId: string, departmentId: string, token: string) => {
    return apiClient.post(`/v1/hospital/ops/incoming/${patientId}/admit`, { departmentId }, { token });
  },
};
