import { createAsyncThunk } from '@reduxjs/toolkit';

import Api from '@northern.tech/store/api/general-api';

import { withApiError } from '@/utils/api';
import type { CfeAttribute, InventoryMapping } from './types';

const inventoryUrl = '/advancedreports/inventory';

// Shape of a single raw variable from the backend. It carries the plain name
// in `attribute_name`
interface RawVariable {
  [key: string]: unknown;
  attribute_name: string;
  category?: string;
  id?: string;
  type?: CfeAttribute['type'];
}

export const getInventoryVariables = createAsyncThunk(
  'inventory/getVariables',
  withApiError<InventoryMapping>(async () => {
    const { data } = await Api.get<Record<string, RawVariable> | RawVariable[]>(`${inventoryUrl}/variables`);
    const mapping: InventoryMapping = {};
    Object.values(data ?? {}).forEach(raw => {
      const label = raw.attribute_name;
      mapping[label] = {
        ...raw,
        label,
        id_key: raw.id,
        // Keep the "attribute_name=" prefix the payload helpers strip; `label`
        // stays the clean backend key.
        attribute_name: `attribute_name=${label}`,
        type: (raw.type as CfeAttribute['type']) || 'string',
        source_table: 'inventory'
      };
    });
    return mapping;
  })
);
