import { api } from '@/services/api'

export type LeadStage = 'new' | 'contacted' | 'qualified' | 'proposal' | 'won' | 'lost'

export interface CrmActivity {
  id: number
  lead_id: number
  type: string
  subject: string
  description: string | null
  activity_date: string
  next_follow_up_at: string | null
}

export interface Lead {
  id: number
  customer_id: number | null
  name: string
  company_name: string | null
  email: string | null
  phone: string | null
  source: string | null
  stage: LeadStage
  deal_value: string
  next_follow_up_at: string | null
  notes: string | null
  status: string
  activities?: CrmActivity[]
}

export interface CrmSummary {
  total_leads: number
  open_leads: number
  won_leads: number
  pipeline_value: string
}

export interface LeadFilters {
  page?: number
  per_page?: number
}

export interface PaginationMeta {
  current_page: number
  from: number | null
  last_page: number
  per_page: number
  to: number | null
  total: number
}

export interface Paginated<T> {
  data: T[]
  meta: PaginationMeta
}

export const crmService = {
  async summary() {
    const { data } = await api.get<{ data: CrmSummary }>('/crm/summary')

    return data.data
  },

  async leads() {
    const { data } = await api.get<{ data: Lead[] }>('/crm/leads')

    return data.data
  },

  async paginatedLeads(filters: LeadFilters = {}) {
    const { data } = await api.get<{ data: Paginated<Lead> }>('/crm/leads', {
      params: filters,
    })

    return data.data
  },

  async createLead(payload: {
    name: string
    company_name?: string
    email?: string
    phone?: string
    source?: string
    stage?: LeadStage
    deal_value?: number
    next_follow_up_at?: string
    notes?: string
  }) {
    const { data } = await api.post<{ data: Lead }>('/crm/leads', payload)

    return data.data
  },

  async updateLead(lead: Lead, payload: Partial<Pick<Lead, 'stage' | 'status' | 'next_follow_up_at' | 'notes'>>) {
    const { data } = await api.patch<{ data: Lead }>(`/crm/leads/${lead.id}`, payload)

    return data.data
  },

  async addActivity(lead: Lead, payload: {
    type?: string
    subject: string
    description?: string
    activity_date?: string
    next_follow_up_at?: string
  }) {
    const { data } = await api.post<{ data: CrmActivity }>(`/crm/leads/${lead.id}/activities`, payload)

    return data.data
  },

  async convertLead(lead: Lead) {
    const { data } = await api.post('/crm/leads/' + lead.id + '/convert')

    return data.data
  },
}
