// Auto-generated by DjangoCFG - see CLAUDE.md
/**
 * Typed fetchers for Web Push
 *
 * Universal functions that work in any environment:
 * - Next.js (App Router / Pages Router / Server Components)
 * - React Native
 * - Node.js backend
 *
 * These fetchers use Zod schemas for runtime validation.
 *
 * Usage:
 * ```typescript
 * // Configure API once (in your app entry point)
 * import { configureAPI } from '../../api-instance'
 * configureAPI({ baseUrl: 'https://api.example.com' })
 *
 * // Then use fetchers anywhere
 * const users = await getUsers({ page: 1 })
 *
 * // With SWR
 * const { data } = useSWR(['users', params], () => getUsers(params))
 *
 * // With React Query
 * const { data } = useQuery(['users', params], () => getUsers(params))
 *
 * // In Server Component or SSR (pass custom client)
 * import { API } from '../../index'
 * const api = new API('https://api.example.com')
 * const users = await getUsers({ page: 1 }, api)
 * ```
 */
import { consola } from 'consola'
import { SendPushRequestRequestSchema, type SendPushRequestRequest } from '../schemas/SendPushRequestRequest.schema'
import { SendPushResponseSchema, type SendPushResponse } from '../schemas/SendPushResponse.schema'
import { SubscribeRequestRequestSchema, type SubscribeRequestRequest } from '../schemas/SubscribeRequestRequest.schema'
import { SubscribeResponseSchema, type SubscribeResponse } from '../schemas/SubscribeResponse.schema'
import { VapidPublicKeyResponseSchema, type VapidPublicKeyResponse } from '../schemas/VapidPublicKeyResponse.schema'
import { getAPIInstance } from '../../api-instance'

/**
 * Send push notification
 *
 * @method POST
 * @path /cfg/webpush/send/
 */
export async function createWebpushSendCreate(  data: SendPushRequestRequest,  client?: any
): Promise<SendPushResponse> {
  const api = client || getAPIInstance()
  const response = await api.web_push.webpushSendCreate(data)
  try {
    return SendPushResponseSchema.parse(response)
  } catch (error) {
    // Zod validation error - log detailed information
    consola.error('❌ Zod Validation Failed');
    consola.box(`createWebpushSendCreate\nPath: /cfg/webpush/send/\nMethod: POST`);

    if (error instanceof Error && 'issues' in error && Array.isArray((error as any).issues)) {
      consola.error('Validation Issues:');
      (error as any).issues.forEach((issue: any, index: number) => {
        consola.error(`  ${index + 1}. ${issue.path.join('.') || 'root'}`);
        consola.error(`     ├─ Message: ${issue.message}`);
        if (issue.expected) consola.error(`     ├─ Expected: ${issue.expected}`);
        if (issue.received) consola.error(`     └─ Received: ${issue.received}`);
      });
    }

    consola.error('Response data:', response);

    // Dispatch browser CustomEvent (only if window is defined)
    if (typeof window !== 'undefined' && error instanceof Error && 'issues' in error) {
      try {
        const event = new CustomEvent('zod-validation-error', {
          detail: {
            operation: 'createWebpushSendCreate',
            path: '/cfg/webpush/send/',
            method: 'POST',
            error: error,
            response: response,
            timestamp: new Date(),
          },
          bubbles: true,
          cancelable: false,
        });
        window.dispatchEvent(event);
      } catch (eventError) {
        // Silently fail - event dispatch should never crash the app
        consola.warn('Failed to dispatch validation error event:', eventError);
      }
    }

    // Re-throw the error
    throw error;
  }
}


/**
 * Subscribe to push notifications
 *
 * @method POST
 * @path /cfg/webpush/subscribe/
 */
export async function createWebpushSubscribeCreate(  data: SubscribeRequestRequest,  client?: any
): Promise<SubscribeResponse> {
  const api = client || getAPIInstance()
  const response = await api.web_push.webpushSubscribeCreate(data)
  try {
    return SubscribeResponseSchema.parse(response)
  } catch (error) {
    // Zod validation error - log detailed information
    consola.error('❌ Zod Validation Failed');
    consola.box(`createWebpushSubscribeCreate\nPath: /cfg/webpush/subscribe/\nMethod: POST`);

    if (error instanceof Error && 'issues' in error && Array.isArray((error as any).issues)) {
      consola.error('Validation Issues:');
      (error as any).issues.forEach((issue: any, index: number) => {
        consola.error(`  ${index + 1}. ${issue.path.join('.') || 'root'}`);
        consola.error(`     ├─ Message: ${issue.message}`);
        if (issue.expected) consola.error(`     ├─ Expected: ${issue.expected}`);
        if (issue.received) consola.error(`     └─ Received: ${issue.received}`);
      });
    }

    consola.error('Response data:', response);

    // Dispatch browser CustomEvent (only if window is defined)
    if (typeof window !== 'undefined' && error instanceof Error && 'issues' in error) {
      try {
        const event = new CustomEvent('zod-validation-error', {
          detail: {
            operation: 'createWebpushSubscribeCreate',
            path: '/cfg/webpush/subscribe/',
            method: 'POST',
            error: error,
            response: response,
            timestamp: new Date(),
          },
          bubbles: true,
          cancelable: false,
        });
        window.dispatchEvent(event);
      } catch (eventError) {
        // Silently fail - event dispatch should never crash the app
        consola.warn('Failed to dispatch validation error event:', eventError);
      }
    }

    // Re-throw the error
    throw error;
  }
}


/**
 * Get VAPID public key
 *
 * @method GET
 * @path /cfg/webpush/vapid/
 */
export async function getWebpushVapidRetrieve(  client?: any
): Promise<VapidPublicKeyResponse> {
  const api = client || getAPIInstance()
  const response = await api.web_push.webpushVapidRetrieve()
  try {
    return VapidPublicKeyResponseSchema.parse(response)
  } catch (error) {
    // Zod validation error - log detailed information
    consola.error('❌ Zod Validation Failed');
    consola.box(`getWebpushVapidRetrieve\nPath: /cfg/webpush/vapid/\nMethod: GET`);

    if (error instanceof Error && 'issues' in error && Array.isArray((error as any).issues)) {
      consola.error('Validation Issues:');
      (error as any).issues.forEach((issue: any, index: number) => {
        consola.error(`  ${index + 1}. ${issue.path.join('.') || 'root'}`);
        consola.error(`     ├─ Message: ${issue.message}`);
        if (issue.expected) consola.error(`     ├─ Expected: ${issue.expected}`);
        if (issue.received) consola.error(`     └─ Received: ${issue.received}`);
      });
    }

    consola.error('Response data:', response);

    // Dispatch browser CustomEvent (only if window is defined)
    if (typeof window !== 'undefined' && error instanceof Error && 'issues' in error) {
      try {
        const event = new CustomEvent('zod-validation-error', {
          detail: {
            operation: 'getWebpushVapidRetrieve',
            path: '/cfg/webpush/vapid/',
            method: 'GET',
            error: error,
            response: response,
            timestamp: new Date(),
          },
          bubbles: true,
          cancelable: false,
        });
        window.dispatchEvent(event);
      } catch (eventError) {
        // Silently fail - event dispatch should never crash the app
        consola.warn('Failed to dispatch validation error event:', eventError);
      }
    }

    // Re-throw the error
    throw error;
  }
}


