import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { createHmac } from 'https://deno.land/std@0.168.0/node/crypto.ts'

export interface WooCommerceProduct {
  id: number
  name: string
  slug: string
  sku: string
  price: string
  regular_price: string
  sale_price: string
  stock_quantity: number | null
  stock_status: string
  description: string
  short_description: string
  type?: string // 'simple', 'variable', 'grouped', 'external'
  categories: Array<{ id: number; name: string }>
  images: Array<{ src: string }>
}

export interface WooCommerceOrder {
  id: number
  order_key: string
  number: string
  status: string
  currency: string
  total: string
  customer_id: number
  billing: {
    first_name: string
    last_name: string
    email: string
    phone: string
  }
  shipping?: {
    first_name: string
    last_name: string
    address_1: string
    address_2: string
    city: string
    postcode: string
    country: string
    state: string
  }
  line_items: Array<{
    id: number
    name: string
    product_id: number
    quantity: number
    total: string
  }>
  date_created: string
  date_modified: string
}

export interface WooCommerceCustomer {
  id: number
  email: string
  first_name: string
  last_name: string
  username: string
  billing: {
    first_name: string
    last_name: string
    company: string
    address_1: string
    address_2: string
    city: string
    postcode: string
    country: string
    state: string
    email: string
    phone: string
  }
  shipping?: {
    first_name: string
    last_name: string
    company: string
    address_1: string
    address_2: string
    city: string
    postcode: string
    country: string
    state: string
  }
  orders_count?: number
  total_spent?: string
  date_created: string
  date_modified: string
}

// Generate OAuth 1.0a signature for WooCommerce API
function generateOAuthSignature(
  method: string,
  url: string,
  params: Record<string, string>,
  consumerSecret: string
): string {
  // Sort parameters
  const sortedParams = Object.keys(params)
    .sort()
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')

  // Create signature base string
  const signatureBaseString = [
    method.toUpperCase(),
    encodeURIComponent(url),
    encodeURIComponent(sortedParams)
  ].join('&')

  // Create signing key (no token secret for WooCommerce)
  const signingKey = `${encodeURIComponent(consumerSecret)}&`

  // Generate signature
  const signature = createHmac('sha256', signingKey)
    .update(signatureBaseString)
    .digest('base64')

  return signature
}

// Make authenticated API request to WooCommerce
export async function wooCommerceApiRequest(
  storeId: string,
  endpoint: string,
  method: string = 'GET',
  body?: any
): Promise<any> {
  const supabaseUrl = Deno.env.get('SUPABASE_URL')!
  const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
  const supabase = createClient(supabaseUrl, supabaseServiceKey)

  // Get store credentials
  const { data: store, error: storeError } = await supabase
    .from('stores')
    .select('store_name, store_url, api_key, api_secret')
    .eq('id', storeId)
    .eq('platform_name', 'woocommerce')
    .single()

  if (storeError || !store) {
    throw new Error('WooCommerce store not found')
  }

  if (!store.api_key || !store.api_secret) {
    throw new Error('WooCommerce credentials not found')
  }

  // Build full API URL with query parameters
  const fullApiUrl = `${store.store_url}/wp-json/wc/v3${endpoint}`

  // Parse URL to separate base URL and query parameters
  const urlObj = new URL(fullApiUrl)
  const baseUrl = `${urlObj.origin}${urlObj.pathname}`

  // Extract query parameters from URL
  const queryParams: Record<string, string> = {}
  urlObj.searchParams.forEach((value, key) => {
    queryParams[key] = value
  })

  // Generate OAuth parameters
  const oauthParams: Record<string, string> = {
    oauth_consumer_key: store.api_key,
    oauth_timestamp: Math.floor(Date.now() / 1000).toString(),
    oauth_nonce: crypto.randomUUID().replace(/-/g, ''),
    oauth_signature_method: 'HMAC-SHA256'
  }

  // Combine OAuth params and query params for signature generation
  const allParams = { ...oauthParams, ...queryParams }

  // Generate signature using base URL (without query params) and all parameters
  const signature = generateOAuthSignature(method, baseUrl, allParams, store.api_secret)
  oauthParams.oauth_signature = signature

  // Build authorization header
  const authHeader = 'OAuth ' + Object.keys(oauthParams)
    .map(key => `${key}="${encodeURIComponent(oauthParams[key])}"`)
    .join(', ')

  // Make request
  const options: RequestInit = {
    method,
    headers: {
      'Authorization': authHeader,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }

  if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
    options.body = JSON.stringify(body)
  }

  try {
    // Use the full URL with query parameters
    const response = await fetch(fullApiUrl, options)

    if (!response.ok) {
      const errorText = await response.text()
      console.error(`[WooCommerce] API error (${response.status}):`, errorText)

      // Handle rate limiting
      if (response.status === 429) {
        throw new Error('Rate limit exceeded - please try again later')
      }

      // Handle authentication errors
      if (response.status === 401 || response.status === 403) {
        throw new Error('Authentication failed - credentials may be invalid')
      }

      throw new Error(`API request failed with status ${response.status}`)
    }

    const data = await response.json()
    return data
  } catch (error) {
    console.error('[WooCommerce] API request error:', error)
    throw error
  }
}

// Fetch products from WooCommerce
export async function fetchProducts(
  storeId: string,
  page: number = 1,
  perPage: number = 25
): Promise<WooCommerceProduct[]> {
  return wooCommerceApiRequest(
    storeId,
    `/products?page=${page}&per_page=${perPage}`,
    'GET'
  )
}

// Fetch a single product
export async function fetchProduct(storeId: string, productId: number): Promise<WooCommerceProduct> {
  return wooCommerceApiRequest(storeId, `/products/${productId}`, 'GET')
}

// Fetch orders from WooCommerce
export interface WooCommerceOrderFilters {
  status?: string;
  customer?: string;  // Customer ID or email
  after?: string;     // ISO 8601 datetime - created after
  before?: string;    // ISO 8601 datetime - created before
  modified_after?: string;  // ISO 8601 datetime - modified after
  modified_before?: string; // ISO 8601 datetime - modified before
}

export async function fetchOrders(
  storeId: string,
  page: number = 1,
  perPage: number = 25,
  filters?: WooCommerceOrderFilters
): Promise<WooCommerceOrder[]> {
  let endpoint = `/orders?page=${page}&per_page=${perPage}`

  if (filters) {
    if (filters.status) {
      endpoint += `&status=${filters.status}`
    }
    if (filters.customer) {
      endpoint += `&customer=${encodeURIComponent(filters.customer)}`
    }
    if (filters.after) {
      endpoint += `&after=${encodeURIComponent(filters.after)}`
    }
    if (filters.before) {
      endpoint += `&before=${encodeURIComponent(filters.before)}`
    }
    if (filters.modified_after) {
      endpoint += `&modified_after=${encodeURIComponent(filters.modified_after)}`
    }
    if (filters.modified_before) {
      endpoint += `&modified_before=${encodeURIComponent(filters.modified_before)}`
    }
  }

  return wooCommerceApiRequest(storeId, endpoint, 'GET')
}

// Fetch a single order
export async function fetchOrder(storeId: string, orderId: number): Promise<WooCommerceOrder> {
  return wooCommerceApiRequest(storeId, `/orders/${orderId}`, 'GET')
}

export interface WooCommerceCustomerFilters {
  email?: string;    // Filter by customer email
  search?: string;   // Search by customer name or email
}

// Fetch customers from WooCommerce
export async function fetchCustomers(
  storeId: string,
  page: number = 1,
  perPage: number = 25,
  filters?: WooCommerceCustomerFilters
): Promise<WooCommerceCustomer[]> {
  let endpoint = `/customers?page=${page}&per_page=${perPage}`

  if (filters) {
    if (filters.email) {
      endpoint += `&email=${encodeURIComponent(filters.email)}`
    }
    if (filters.search) {
      endpoint += `&search=${encodeURIComponent(filters.search)}`
    }
  }

  return wooCommerceApiRequest(storeId, endpoint, 'GET')
}

// Fetch a single customer
export async function fetchCustomer(storeId: string, customerId: number): Promise<WooCommerceCustomer> {
  return wooCommerceApiRequest(storeId, `/customers/${customerId}`, 'GET')
}

// Test WooCommerce connection
export async function testConnection(storeId: string): Promise<{ success: boolean; message: string; data?: any }> {
  try {
    const data = await wooCommerceApiRequest(storeId, '/system_status', 'GET')
    return {
      success: true,
      message: 'Connection successful',
      data
    }
  } catch (error) {
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Connection test failed'
    }
  }
}

// Get store settings
export async function getStoreSettings(storeId: string): Promise<any> {
  return wooCommerceApiRequest(storeId, '/settings/general', 'GET')
}

// Search products
export async function searchProducts(
  storeId: string,
  searchTerm: string,
  page: number = 1,
  perPage: number = 10
): Promise<WooCommerceProduct[]> {
  return wooCommerceApiRequest(
    storeId,
    `/products?search=${encodeURIComponent(searchTerm)}&page=${page}&per_page=${perPage}`,
    'GET'
  )
}
