/**
 * Store API
 * 
 * API layer for the Feature Store.
 * Manages feature activation/deactivation in the root mandate's shared instances.
 */

import api from '../api';

export interface StoreFeatureInstance {
  instanceId: string;
  mandateId: string;
  mandateName: string;
  label: string;
  isActive: boolean;
}

export interface StoreFeature {
  featureCode: string;
  label: string;
  icon: string;
  description: string;
  instances: StoreFeatureInstance[];
  canActivate: boolean;
}

export interface StoreActivateResponse {
  featureCode: string;
  instanceId: string;
  featureAccessId: string;
  roleId: string | null;
  activated: boolean;
}

export interface StoreDeactivateResponse {
  featureCode: string;
  instanceId: string;
  deactivated: boolean;
}

export interface UserMandate {
  id: string;
  name: string;
  label: string;
}

export interface SubscriptionInfo {
  plan: string | null;
  status: string | null;
  maxDataVolumeMB: number | null;
  maxFeatureInstances: number | null;
  includedModules: number;
  budgetAiCHF: number | null;
  budgetAiPerUserCHF: number | null;
  currentFeatureInstances: number;
  trialEndsAt: string | null;
}

export async function fetchStoreFeatures(): Promise<StoreFeature[]> {
  const response = await api.get<StoreFeature[]>('/api/store/features');
  return response.data;
}

export async function fetchUserMandates(): Promise<UserMandate[]> {
  const response = await api.get<UserMandate[]>('/api/store/mandates');
  return response.data;
}

export async function fetchSubscriptionInfo(mandateId?: string): Promise<SubscriptionInfo> {
  const params = mandateId ? { mandateId } : {};
  const response = await api.get<SubscriptionInfo>('/api/store/subscription-info', { params });
  return response.data;
}

export async function activateStoreFeature(featureCode: string, mandateId?: string): Promise<StoreActivateResponse> {
  const response = await api.post<StoreActivateResponse>('/api/store/activate', { featureCode, mandateId });
  return response.data;
}

export async function deactivateStoreFeature(featureCode: string, mandateId: string, instanceId: string): Promise<StoreDeactivateResponse> {
  const response = await api.post<StoreDeactivateResponse>('/api/store/deactivate', { featureCode, mandateId, instanceId });
  return response.data;
}
