import { api } from '../api'
import { Contact } from './contacts'

export interface Supplier extends Contact {
  customFields?: {
    supplierCode?: string
    supplierCategory?: string
    supplierCategories?: string[]
    paymentTerms?: string
    bankName?: string
    bankAccount?: string
    contactPosition?: string
    notes?: string
    [key: string]: any
  }
}

export interface SupplierFilters {
  search?: string
  status?: string
  rating?: number
  category?: string
  page?: number
  pageSize?: number
}

export interface SuppliersResponse {
  suppliers: Supplier[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

export interface SupplierStats {
  total: number
  active: number
  inactive: number
  blocked: number
}

export interface CreateSupplierData {
  name: string
  nameAr?: string
  email?: string
  phone?: string
  mobile?: string
  website?: string
  companyName?: string
  companyNameAr?: string
  taxNumber?: string
  commercialRegister?: string
  address?: string
  city?: string
  country?: string
  postalCode?: string
  categories?: string[]
  tags?: string[]
  source?: string
  rating?: number
  customFields?: Supplier['customFields']
}

export interface UpdateSupplierData extends Partial<CreateSupplierData> {
  status?: string
}

const buildParams = (filters: SupplierFilters = {}) => {
  const params = new URLSearchParams()
  if (filters.search) params.append('search', filters.search)
  if (filters.status) params.append('status', filters.status)
  if (filters.rating) params.append('rating', filters.rating.toString())
  if (filters.category) params.append('category', filters.category)
  if (filters.page) params.append('page', filters.page.toString())
  if (filters.pageSize) params.append('pageSize', filters.pageSize.toString())
  return params
}

export const suppliersAPI = {
  getAll: async (filters: SupplierFilters = {}): Promise<SuppliersResponse> => {
    const params = buildParams(filters)
    const response = await api.get(`/suppliers?${params.toString()}`)
    const { data, pagination } = response.data
    return {
      suppliers: data || [],
      total: pagination?.total || 0,
      page: pagination?.page || 1,
      pageSize: pagination?.pageSize || 20,
      totalPages: pagination?.totalPages || 0,
    }
  },

  getStats: async (): Promise<SupplierStats> => {
    const response = await api.get('/suppliers/stats')
    return response.data.data
  },

  getById: async (id: string): Promise<Supplier> => {
    const response = await api.get(`/suppliers/${id}`)
    return response.data.data
  },

  create: async (data: CreateSupplierData): Promise<Supplier> => {
    const response = await api.post('/suppliers', data)
    return response.data.data
  },

  update: async (id: string, data: UpdateSupplierData): Promise<Supplier> => {
    const response = await api.put(`/suppliers/${id}`, data)
    return response.data.data
  },

  archive: async (id: string, reason?: string): Promise<Supplier> => {
    const response = await api.post(`/suppliers/${id}/archive`, { reason })
    return response.data.data
  },

  export: async (filters: SupplierFilters = {}): Promise<Blob> => {
    const params = buildParams(filters)
    const response = await api.get(`/suppliers/export?${params.toString()}`, { responseType: 'blob' })
    return response.data
  }
}
