import { BaseApiService } from '@/services/api/base';
import { BaseApiResponse } from '@/types/api/api-general';
import {
  CreateProductWarehousePayload,
  ProductWarehouse,
  UpdateProductWarehousePayload,
} from '@/types/api/inventory/product-warehouse';
import {
  CreateMovementPayload,
  Movement,
} from '@/types/api/inventory/movement';
import {
  CreateInventoryAdjustmentPayload,
  InventoryAdjustment,
} from '@/types/api/inventory/adjustment';
import { InventoryProduct, StockLog } from '@/types/api/inventory/product';
import { httpClient } from '../http/client';
import { formatDate } from '@/lib/helper';

export const ProductWarehouseApi = new BaseApiService<
  ProductWarehouse,
  CreateProductWarehousePayload,
  UpdateProductWarehousePayload
>('/inventory/product-warehouses');

export class MovementApiService extends BaseApiService<
  Movement,
  CreateMovementPayload,
  unknown
> {
  constructor(basePath: string) {
    super(basePath);
  }

  async createMovement(
    payload: CreateMovementPayload
  ): Promise<BaseApiResponse<Movement> | undefined> {
    const formData = new FormData();

    // Append data as JSON string
    formData.append('data', JSON.stringify(payload.data));

    // Append documents if any
    if (payload.documents && payload.documents.length > 0) {
      payload.documents.forEach((file) => {
        formData.append('documents', file);
      });
    }

    return await this.customRequest<BaseApiResponse<Movement>>('', {
      method: 'POST',
      payload: formData as unknown as Record<string, unknown>,
    });
  }
}

export const MovementApi = new MovementApiService('/inventory/transfers');

export const InventoryAdjustmentApi = new BaseApiService<
  InventoryAdjustment,
  CreateInventoryAdjustmentPayload,
  unknown
>('/inventory/adjustments');

export const InventoryProductApi = new BaseApiService<
  InventoryProduct,
  unknown,
  unknown
>('/inventory/product-stocks');

export class StockLogService extends BaseApiService<
  StockLog,
  unknown,
  unknown
> {
  constructor(basePath: string = '/inventory/stock-logs') {
    super(basePath);
  }

  async exportToExcel(warehouseName: string, initialQueryString: string) {
    const params = new URLSearchParams(initialQueryString);

    params.set('export', 'excel');
    params.set('page', '1');
    params.set('limit', '99999999999');

    const queryString = `?${params.toString()}`;

    const res = await httpClient<Blob>(`${this.basePath}${queryString}`, {
      method: 'GET',
      responseType: 'blob',
    });

    const url = window.URL.createObjectURL(new Blob([res]));
    const link = document.createElement('a');
    link.href = url;

    const fileName = `informasi-stok-produk-${warehouseName.toLowerCase().replaceAll(' ', '-')}-${formatDate(Date.now(), 'DD-MM-YYYY')}.xlsx`;
    link.setAttribute('download', fileName);

    document.body.appendChild(link);
    link.click();
    link.remove();
  }
}

export const StockLogApi = new StockLogService('/inventory/stock-logs');
