import api from '../utils/request'

export type MessageType = 'MESSAGE' | 'NOTIFICATION'
export type ContentType = 'TEXT' | 'IMAGE' | 'VIDEO' | 'FILE' | 'USER_NOTIFICATION'

export interface AdminMessageItem {
  id: number
  type: MessageType
  content_type: ContentType
  title: string
  content: string
  action_url?: string | null
  action_text?: string | null
  is_read: boolean
  created_at: string
  read_at?: string | null

  sender_id?: number | null
  sender_mobile?: string | null
  sender_name?: string | null

  receiver_id: number
  receiver_mobile?: string | null
  receiver_name?: string | null

  app_id?: number | null
  app_app_id?: string | null
  app_name?: string | null
}

export interface AdminMessageList {
  total: number
  items: AdminMessageItem[]
}

export interface AdminMessageQueryParams {
  skip?: number
  limit?: number
  keyword?: string
  sender_user_ids?: number[]
  sender_app_ids?: number[]
  receiver_user_ids?: number[]
  msg_type?: MessageType
  content_type?: ContentType
  is_read?: boolean
  start_date?: string
  end_date?: string
}

const serializeParams = (params: Record<string, any>): string => {
  const parts: string[] = []
  Object.entries(params).forEach(([key, value]) => {
    if (value === undefined || value === null || value === '') return
    if (Array.isArray(value)) {
      if (value.length === 0) return
      value.forEach((v) => {
        if (v === undefined || v === null || v === '') return
        parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`)
      })
    } else {
      parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
    }
  })
  return parts.join('&')
}

export const searchAdminMessages = (params: AdminMessageQueryParams) => {
  return api.get<AdminMessageList>('/messages/admin/search', {
    params,
    paramsSerializer: serializeParams,
  })
}

export interface AdminAppOption {
  id: number
  app_id: string
  app_name: string | null
}

export const searchApps = (q: string) => {
  return api.get<AdminAppOption[]>('/apps/search', {
    params: { q: q || undefined, limit: 50 },
  })
}
