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

import Api from '@/api';

import { notify } from '../../../common/notify';
import type { Container, ContainerImage, ContainersSummary, ListResponse } from './types';

export interface ListArgs {
  hostkey: string;
  page: number;
  perPage: number;
  sort?: string;
  order?: 'asc' | 'desc';
}

const buildParams = ({ hostkey, page, perPage, sort, order }: ListArgs) => ({
  hostkey,
  page,
  per_page: perPage,
  ...(sort ? { sort } : {}),
  ...(order ? { order } : {})
});

export const fetchContainersSummary = createAsyncThunk(
  'containers/fetchSummary',
  async (hostkey: string) => {
    try {
      const { data } = await Api.get<ContainersSummary>(`/containers/summary/${hostkey}`);
      return { hostkey, data };
    } catch (err) {
      notify.error(`Failed to load containers summary: ${(err as Error).message}`);
      throw err;
    }
  }
);

export const fetchContainers = createAsyncThunk(
  'containers/fetchContainers',
  async (args: ListArgs) => {
    try {
      const { data } = await Api.get<ListResponse<Container>>('/containers/list', {
        params: buildParams(args)
      });
      return { hostkey: args.hostkey, data };
    } catch (err) {
      // Error is surfaced in the Containers table, so no toast needed here.
      throw err;
    }
  }
);

export const fetchContainerImages = createAsyncThunk(
  'containers/fetchImages',
  async (args: ListArgs) => {
    try {
      const { data } = await Api.get<ListResponse<ContainerImage>>('/containers/images', {
        params: buildParams(args)
      });
      return { hostkey: args.hostkey, data };
    } catch (err) {
      // Error is surfaced in the Images table, so no toast needed here.
      throw err;
    }
  }
);
