import { api } from '../api'

export interface Tender {
  id: string
  tenderNumber?: string | null
  issueNumber?: string | null
  issuingBodyName: string
  title: string

  termsValue: number
  bondValue: number

  // extra fields stored inside notes metadata for now
  initialBondValue?: number | null
  finalBondValue?: number | null
  finalBondRefundPeriod?: string | null
  siteVisitRequired?: boolean
  siteVisitLocation?: string | null
  termsPickupProvince?: string | null

  announcementDate?: string | null
  closingDate?: string | null
  announcementLink?: string
  source: string
  sourceOther?: string
  announcementType: string
  notes?: string
  status: string
  contactId?: string
  contact?: any
  createdById: string
  createdBy?: any
  createdAt: string
  updatedAt: string
  directives?: TenderDirective[]
  attachments?: any[]
  _count?: { directives: number }
}


export interface TenderDirective {
  id: string
  tenderId: string
  type: string
  notes?: string
  assignedToEmployeeId: string
  assignedToEmployee?: any
  issuedById: string
  issuedBy?: any
  status: string
  completedAt?: string
  completionNotes?: string
  completedById?: string
  createdAt: string
  updatedAt: string
  attachments?: any[]
}

export interface CreateTenderData {
  tenderNumber?: string | null
  issueNumber?: string
  issuingBodyName: string
  title: string

  termsValue: number
  bondValue: number

  // extra UI/backend fields without DB migration
  initialBondValue?: number
  finalBondValue?: number
  finalBondRefundPeriod?: string
  siteVisitRequired?: boolean
  siteVisitLocation?: string
  termsPickupProvince?: string

  announcementDate?: string | null
  closingDate?: string | null
  announcementLink?: string
  source: string
  sourceOther?: string
  announcementType: string
  notes?: string
  contactId?: string
}

export interface CreateDirectiveData {
  type: string
  assignedToEmployeeId: string
  notes?: string
}

export interface TenderFilters {
  search?: string
  status?: string
  source?: string
  announcementType?: string
  page?: number
  pageSize?: number
}

export interface TendersResponse {
  data: Tender[]
  pagination: {
    total: number
    page: number
    pageSize: number
    totalPages: number
  }
}

export const tendersAPI = {
  getAll: async (filters: TenderFilters = {}): Promise<{ tenders: Tender[]; total: number; page: number; pageSize: number; totalPages: number }> => {
    const params = new URLSearchParams()
    if (filters.search) params.append('search', filters.search)
    if (filters.status) params.append('status', filters.status)
    if (filters.source) params.append('source', filters.source)
    if (filters.announcementType) params.append('announcementType', filters.announcementType)
    if (filters.page) params.append('page', filters.page.toString())
    if (filters.pageSize) params.append('pageSize', filters.pageSize.toString())

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

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

  create: async (data: CreateTenderData): Promise<{ tender: Tender; possibleDuplicates?: Tender[] }> => {
    const response = await api.post('/tenders', data)
    return response.data.data
  },

  update: async (id: string, data: Partial<CreateTenderData>): Promise<Tender> => {
    const response = await api.put(`/tenders/${id}`, data)
    return response.data.data
  },

  checkDuplicates: async (data: Partial<CreateTenderData>): Promise<Tender[]> => {
    const response = await api.post('/tenders/check-duplicates', data)
    return response.data.data
  },

  getHistory: async (id: string): Promise<any[]> => {
    const response = await api.get(`/tenders/${id}/history`)
    return response.data.data
  },

  createDirective: async (tenderId: string, data: CreateDirectiveData): Promise<TenderDirective> => {
    const response = await api.post(`/tenders/${tenderId}/directives`, data)
    return response.data.data
  },

  updateDirective: async (directiveId: string, data: { status?: string; completionNotes?: string }): Promise<TenderDirective> => {
    const response = await api.put(`/tenders/directives/${directiveId}`, data)
    return response.data.data
  },

  convertToDeal: async (tenderId: string, data: { contactId: string; pipelineId: string; ownerId?: string }): Promise<any> => {
    const response = await api.post(`/tenders/${tenderId}/convert-to-deal`, data)
    return response.data.data
  },

  delete: async (id: string): Promise<void> => {
    await api.delete(`/tenders/${id}`)
  },

  uploadTenderAttachment: async (tenderId: string, file: File, category?: string): Promise<any> => {
    const formData = new FormData()
    formData.append('file', file)
    if (category) formData.append('category', category)
    const response = await api.post(`/tenders/${tenderId}/attachments`, formData, {
      headers: { 'Content-Type': undefined as any },
    })
    return response.data.data
  },

  uploadDirectiveAttachment: async (directiveId: string, file: File, category?: string): Promise<any> => {
    const formData = new FormData()
    formData.append('file', file)
    if (category) formData.append('category', category)
    const response = await api.post(`/tenders/directives/${directiveId}/attachments`, formData, {
      headers: { 'Content-Type': undefined as any },
    })
    return response.data.data
  },

  deleteAttachment: async (attachmentId: string): Promise<void> => {
  await api.delete(`/tenders/attachments/${attachmentId}`)
  },

  getSourceValues: async (): Promise<string[]> => {
    const response = await api.get('/tenders/source-values')
    return response.data.data
  },

  getAnnouncementTypeValues: async (): Promise<string[]> => {
    const response = await api.get('/tenders/announcement-type-values')
    return response.data.data
  },

  getDirectiveTypeValues: async (): Promise<string[]> => {
    const response = await api.get('/tenders/directive-type-values')
    return response.data.data
  },

  // Minimal employee list (id + names only) safe to call without
  // hr:employees:read. Used only to populate the directive assignee dropdown.
  getAssignableEmployees: async (): Promise<Array<{
    id: string
    firstName: string
    lastName: string
    firstNameAr: string | null
    lastNameAr: string | null
  }>> => {
    const response = await api.get('/tenders/assignable-employees')
    return response.data.data
  },
}