import { api } from '../api'

export interface Employee {
  id: string
  uniqueEmployeeId: string
  firstName: string
  lastName: string
  firstNameAr?: string
  lastNameAr?: string
  email: string
  phone?: string
  mobile: string
  dateOfBirth?: string
  gender?: string
  nationality?: string
  nationalId?: string
  passportNumber?: string
  employmentType: string
  contractType?: string
  hireDate: string
  endDate?: string
  departmentId: string
  department?: any
  positionId: string
  position?: any
  reportingToId?: string
  reportingTo?: any
  baseSalary: number
  status: string
  createdAt: string
  updatedAt: string
}

export interface CreateEmployeeData {
  firstName: string
  lastName: string
  firstNameAr?: string
  lastNameAr?: string
  email: string
  phone?: string
  mobile: string
  dateOfBirth?: string
  gender?: string
  nationality?: string
  nationalId?: string
  employmentType: string
  contractType?: string
  hireDate: string
  departmentId: string
  positionId: string
  reportingToId?: string
  baseSalary: number
}

export interface UpdateEmployeeData extends Partial<CreateEmployeeData> {}

export interface EmployeeFilters {
  search?: string
  departmentId?: string
  positionId?: string
  status?: string
  page?: number
  pageSize?: number
}

export interface EmployeesResponse {
  employees: Employee[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

export const employeesAPI = {
  // Get all employees with filters and pagination
  getAll: async (filters: EmployeeFilters = {}): Promise<EmployeesResponse> => {
    const params = new URLSearchParams()
    if (filters.search) params.append('search', filters.search)
    if (filters.departmentId) params.append('departmentId', filters.departmentId)
    if (filters.positionId) params.append('positionId', filters.positionId)
    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(`/hr/employees?${params.toString()}`)
    const { data, pagination } = response.data
    const employees = (data || []).map((e: any) => ({
      ...e,
      baseSalary: e.baseSalary ?? e.basicSalary ?? 0,
    }))
    return {
      employees,
      total: pagination?.total || 0,
      page: pagination?.page || 1,
      pageSize: pagination?.pageSize || 20,
      totalPages: pagination?.totalPages || 0,
    }
  },

  // Get single employee by ID
  getById: async (id: string): Promise<Employee> => {
    const response = await api.get(`/hr/employees/${id}`)
    const e = response.data.data
    return e ? { ...e, baseSalary: e.baseSalary ?? e.basicSalary ?? 0 } : e
  },

  // Create new employee
  create: async (data: CreateEmployeeData): Promise<Employee> => {
    const response = await api.post('/hr/employees', data)
    return response.data.data
  },

  // Update existing employee
  update: async (id: string, data: UpdateEmployeeData): Promise<Employee> => {
    const response = await api.put(`/hr/employees/${id}`, data)
    return response.data.data
  },

  // Delete employee
  delete: async (id: string): Promise<void> => {
    await api.delete(`/hr/employees/${id}`)
  }
}

// Departments API
export interface Department {
  id: string
  name: string
  nameAr?: string | null
  code: string
  parentId?: string | null
  parent?: { id: string; name: string; nameAr?: string | null }
  description?: string | null
  isActive?: boolean
  children?: Department[]
  employees?: any[]
  positions?: any[]
  _count?: { children: number; employees: number }
}

export const departmentsAPI = {
  getAll: async (): Promise<any[]> => {
    const response = await api.get('/hr/departments')
    return response.data.data
  },
  getHierarchy: async (): Promise<Department[]> => {
    const response = await api.get('/hr/departments/hierarchy')
    return response.data.data
  },
  create: async (data: { name: string; nameAr?: string; code: string; parentId?: string; description?: string }) => {
    const response = await api.post('/hr/departments', data)
    return response.data.data
  },
  update: async (id: string, data: Partial<{ name: string; nameAr: string; code: string; parentId: string | null; description: string; isActive: boolean }>) => {
    const response = await api.put(`/hr/departments/${id}`, data)
    return response.data.data
  },
  delete: async (id: string) => {
    await api.delete(`/hr/departments/${id}`)
  }
}

// Positions API
export const positionsAPI = {
  getAll: async (): Promise<any[]> => {
    const response = await api.get('/hr/positions')
    return response.data.data
  }
}
