import axios from 'axios'

const API_BASE = import.meta.env.VITE_API_URL || '/api'

const api = axios.create({
  baseURL: API_BASE,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true,
})

export const mealPlannerApi = {
  auth: {
    login: (password: string) => api.post('/auth/login', { password }),
    logout: () => api.post('/auth/logout'),
  },

  profile: {
    get: () => api.get('/profile'),
    update: (data: any) => api.put('/profile', data),
    getMembers: () => api.get('/profile/members'),
    addMember: (data: any) => api.post('/profile/members', data),
    deleteMember: (id: string) => api.delete(`/profile/members/${id}`),
  },

  recipes: {
    list: (params?: any) => api.get('/recipes', { params }),
    recommended: (familyProfileId: string, limit?: number) =>
      api.get('/recipes/recommended', { params: { family_profile_id: familyProfileId, limit } }),
    get: (id: string) => api.get(`/recipes/${id}`),
    create: (data: any) => api.post('/recipes', data),
    delete: (id: string) => api.delete(`/recipes/${id}`),
    listIngredients: () => api.get('/ingredients?limit=500'),
    createIngredient: (data: any) => api.post('/ingredients', data),
  },

  meals: {
    getPlanned: (weekStart?: string) => api.get('/meals', { params: { week_start: weekStart } }),
    get: (id: string) => api.get(`/meals/${id}`),
    getItem: (id: string) => api.get(`/meals/items/${id}`),
    create: (data: any) => api.post('/meals', data),
    lock: (id: string) => api.post(`/meals/${id}/lock`),
    getVotePage: (itemId: string, token: string) => api.get(`/meals/items/${itemId}/vote/${token}`),
    submitVote: (itemId: string, token: string, data: any) => api.post(`/meals/items/${itemId}/vote/${token}`, data),
    swapItem: (itemId: string, newRecipeId: string) => api.post(`/meals/items/${itemId}/swap?new_recipe_id=${newRecipeId}`),
    moveItem: (itemId: string, newDayOfWeek: number, newMealType: string) => api.put(`/meals/items/${itemId}/move`, null, { params: { new_day_of_week: newDayOfWeek, new_meal_type: newMealType } }),
    approveItem: (itemId: string) => api.post(`/meals/items/${itemId}/approve`),
    // Sprint 8: scope ∈ 'this_week' (default) | 'never_again'. The
    // server auto-promotes 'this_week' to permanent block on the 2nd
    // denial within the 90-day decay window; 'never_again' always
    // writes a NeverSuggest row. Response includes
    // promoted_to_permanent: boolean so the UI can show a clear toast.
    denyItem: (itemId: string, opts?: { scope?: 'this_week' | 'never_again' }) =>
      api.post(
        `/meals/items/${itemId}/deny`,
        undefined,
        { params: opts?.scope ? { scope: opts.scope } : {} },
      ),
    deleteItem: (itemId: string) => api.delete(`/meals/items/${itemId}`),
    generateItem: (mealPlanId: string, dayOfWeek: number, mealType: string) =>
      api.post(`/meals/${mealPlanId}/generate-item`, null, { params: { day_of_week: dayOfWeek, meal_type: mealType } }),
    fillEmptySlots: (mealPlanId: string, mealTypes: string[]) =>
      api.post(`/meals/${mealPlanId}/fill-empty-slots`, { meal_types: mealTypes }),
  },

  pantry: {
    list: () => api.get('/pantry'),
    add: (data: any) => api.post('/pantry', data),
    update: (id: string, data: any) => api.put(`/pantry/${id}`, data),
    remove: (id: string) => api.delete(`/pantry/${id}`),
    addBulk: (items: Array<{ ingredient_id: string; quantity?: number; unit?: string }>) =>
      api.post('/pantry/bulk', { items }),
  },

  // Sprint 10: family-facing never-suggest endpoints. These are
  // separate from the existing /api/admin/never-suggest admin path
  // (which still requires the ADMIN_TOKEN). The new public path
  // uses require_session (auto-resolves to the first family profile
  // on the trusted network) and enforces row-level ownership on DELETE
  // (403 if the row belongs to a different family).
  neverSuggest: {
    list: (familyProfileId: string) =>
      api.get('/never-suggest', { params: { family_profile_id: familyProfileId } }),
    add: (data: { family_profile_id: string; recipe_id: string; reason: 'allergy' | 'dislike'; notes?: string }) =>
      api.post('/never-suggest', data),
    remove: (nsId: string) => api.delete(`/never-suggest/${nsId}`),
  },

  shoppingList: {
    get: (weekStart?: string) => api.get('/shopping-list', { params: { week_start: weekStart } }),
    getPrint: () => api.get('/shopping-list/print'),
  },

  admin: {
    triggerScrape: (source?: string, type?: string) => api.post('/admin/scrape', null, { params: { source, scrape_type: type } }),
    getLogs: (params?: any) => api.get('/admin/logs', { params }),
    getLog: (id: string) => api.get(`/admin/logs/${id}`),
    getEmailLogs: (params?: any) => api.get('/admin/email-logs', { params }),
    getMealPlans: (params?: any) => api.get('/admin/meal-plans', { params }),
    getStats: () => api.get('/admin/stats'),
    testEmail: (email: string) => api.post('/admin/test-email', null, { params: { email } }),
    triggerOrchestrate: (step: string, weekStart?: string) => api.post(`/orchestrate/${step}`, null, { params: { week_start: weekStart } }),
  },

  feedback: {
    get: (mealPlanItemId: string) => api.get(`/feedback/${mealPlanItemId}`),
    create: (data: any) => api.post('/feedback', data),
  },
}

export default api
