/**
 * Access Policy Helpers
 *
 * Utilities for checking and enforcing data access policies (GDPR compliance)
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { ToolCallResult } from './mcp-sse.ts';

// Initialize Supabase client
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);

/**
 * Data access policy type
 */
export type DataAccessPolicy = 'sync' | 'api_only' | 'not_allowed';

/**
 * Data type for access control
 */
export type DataType = 'products' | 'customers' | 'orders';

/**
 * Access policy configuration
 */
export interface AccessPolicyConfig {
  productsPolicy: DataAccessPolicy;
  customersPolicy: DataAccessPolicy;
  ordersPolicy: DataAccessPolicy;
  platform: string;
  storeName: string;
}

/**
 * Get access policy configuration for a store
 */
export async function getAccessPolicyConfig(storeId: string): Promise<AccessPolicyConfig | null> {
  // Get store info
  const { data: store, error: storeError } = await supabase
    .from('stores')
    .select('platform_name, store_name')
    .eq('id', storeId)
    .single();

  if (storeError || !store) {
    console.error('[Access Policy] Store not found:', storeId);
    return null;
  }

  // Get sync config with access policy columns
  const { data: syncConfig, error: syncError } = await supabase
    .from('store_sync_config')
    .select('products_access_policy, customers_access_policy, orders_access_policy')
    .eq('store_id', storeId)
    .single();

  // Default to 'sync' if no config exists
  const config = syncConfig || {
    products_access_policy: 'sync',
    customers_access_policy: 'sync',
    orders_access_policy: 'sync'
  };

  return {
    productsPolicy: (config.products_access_policy || 'sync') as DataAccessPolicy,
    customersPolicy: (config.customers_access_policy || 'sync') as DataAccessPolicy,
    ordersPolicy: (config.orders_access_policy || 'sync') as DataAccessPolicy,
    platform: store.platform_name,
    storeName: store.store_name
  };
}

/**
 * Check if access is allowed for a specific data type
 */
export function isAccessAllowed(policy: DataAccessPolicy): boolean {
  return policy !== 'not_allowed';
}

/**
 * Check if sync/cache access is allowed (sync mode)
 */
export function isSyncAllowed(policy: DataAccessPolicy): boolean {
  return policy === 'sync';
}

/**
 * Check if only API access is allowed (api_only mode)
 */
export function isApiOnlyMode(policy: DataAccessPolicy): boolean {
  return policy === 'api_only';
}

/**
 * Create an access denied error response
 */
export function createAccessDeniedError(dataType: DataType): ToolCallResult {
  return {
    content: [{
      type: 'text',
      text: JSON.stringify({
        error: `Access to ${dataType} data is not allowed for this store. The store owner has disabled ${dataType} access.`,
        access_policy: 'not_allowed',
        data_type: dataType
      })
    }],
    isError: true
  };
}

/**
 * Create an API-only notice response
 * This is used when we're making a direct API call due to api_only policy
 */
export function createApiOnlyNotice(dataType: DataType): string {
  return `Note: Fetching ${dataType} directly from store API (api_only mode - no caching)`;
}

/**
 * Get the appropriate access policy for a data type
 */
export function getDataTypePolicy(config: AccessPolicyConfig, dataType: DataType): DataAccessPolicy {
  switch (dataType) {
    case 'products':
      return config.productsPolicy;
    case 'customers':
      return config.customersPolicy;
    case 'orders':
      return config.ordersPolicy;
    default:
      return 'not_allowed';
  }
}

/**
 * Validate access and return appropriate error if not allowed
 * Returns null if access is allowed
 */
export function validateAccess(
  config: AccessPolicyConfig | null,
  dataType: DataType
): ToolCallResult | null {
  if (!config) {
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({ error: 'Store configuration not found' })
      }],
      isError: true
    };
  }

  const policy = getDataTypePolicy(config, dataType);

  if (!isAccessAllowed(policy)) {
    return createAccessDeniedError(dataType);
  }

  return null; // Access is allowed
}
