import { api } from '../api'

export interface Campaign {
  id: string
  campaignNumber: string
  name: string
  nameAr?: string
  type: string // EMAIL, WHATSAPP, SOCIAL, EXHIBITION, MULTI_CHANNEL
  description?: string
  content?: any
  targetAudience?: any
  budget?: number
  actualCost?: number
  expectedROI?: number
  actualROI?: number
  startDate?: string
  endDate?: string
  status: string // PLANNED, ACTIVE, PAUSED, COMPLETED, CANCELLED
  createdAt: string
  updatedAt: string
}

export interface CreateCampaignData {
  name: string
  nameAr?: string
  type: string
  description?: string
  budget?: number
  expectedROI?: number
  startDate?: string
  endDate?: string
}

export interface UpdateCampaignData extends Partial<CreateCampaignData> {
  actualCost?: number
  actualROI?: number
  status?: string
}

export interface CampaignFilters {
  search?: string
  type?: string
  status?: string
  page?: number
  pageSize?: number
}

export interface CampaignsResponse {
  campaigns: Campaign[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

export const campaignsAPI = {
  // Get all campaigns with filters and pagination
  getAll: async (filters: CampaignFilters = {}): Promise<CampaignsResponse> => {
    const params = new URLSearchParams()
    if (filters.search) params.append('search', filters.search)
    if (filters.type) params.append('type', filters.type)
    if (filters.status) params.append('status', filters.status)
    if (filters.page) params.append('page', filters.page.toString())
    if (filters.pageSize) params.append('pageSize', filters.pageSize.toString())

    const response = await api.get(`/marketing/campaigns?${params.toString()}`)
    const { data, pagination } = response.data
    return {
      campaigns: data || [],
      total: pagination?.total || 0,
      page: pagination?.page || 1,
      pageSize: pagination?.pageSize || 20,
      totalPages: pagination?.totalPages || 0,
    }
  },

  // Get single campaign by ID
  getById: async (id: string): Promise<Campaign> => {
    const response = await api.get(`/marketing/campaigns/${id}`)
    return response.data.data
  },

  // Create new campaign
  create: async (data: CreateCampaignData): Promise<Campaign> => {
    const response = await api.post('/marketing/campaigns', data)
    return response.data.data
  },

  // Update existing campaign
  update: async (id: string, data: UpdateCampaignData): Promise<Campaign> => {
    const response = await api.put(`/marketing/campaigns/${id}`, data)
    return response.data.data
  },

  // Delete campaign
  delete: async (id: string): Promise<void> => {
    await api.delete(`/marketing/campaigns/${id}`)
  }
}
