import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';

export type RerunCollection = components['schemas']['RerunCollectionResponseModel'];
export type PagedRerunCollections = components['schemas']['PagedRerunCollectionsResponseModel'];
export type CreateRerunCollectionRequest = components['schemas']['CreateRerunCollectionRequest'];
export type UpdateRerunCollectionRequest = components['schemas']['UpdateRerunCollectionRequest'];

export interface GetRerunCollectionsParams {
  query?: string;
  pageNum?: number;
  pageSize?: number;
}

export function getRerunCollections(params: GetRerunCollectionsParams = {}): Promise<PagedRerunCollections> {
  const searchParams = new URLSearchParams();

  if (params.query != null) {
    searchParams.set('query', params.query);
  }

  if (params.pageNum != null) {
    searchParams.set('pageNum', String(params.pageNum));
  }

  if (params.pageSize != null) {
    searchParams.set('pageSize', String(params.pageSize));
  }

  const queryString = searchParams.toString();

  return request<PagedRerunCollections>(`/api/v1/rerun-collections${queryString ? `?${queryString}` : ''}`);
}

export function getRerunCollection(id: number): Promise<RerunCollection> {
  return request<RerunCollection>(`/api/v1/rerun-collections/${id}`);
}

/** Load a single rerun collection together with its concurrency ETag (issue #253). */
export function getRerunCollectionWithMeta(id: number): Promise<ResponseWithMeta<RerunCollection>> {
  return requestWithMeta<RerunCollection>(`/api/v1/rerun-collections/${id}`);
}

export function createRerunCollection(body: CreateRerunCollectionRequest): Promise<RerunCollection> {
  return request<RerunCollection>('/api/v1/rerun-collections', { body, method: 'POST' });
}

/**
 * Update a rerun collection. Pass the last-seen ETag as `If-Match` to reject a stale overwrite
 * with 412; the resolved value carries the new ETag for a subsequent save (issue #253).
 */
export function updateRerunCollection(
  id: number,
  body: UpdateRerunCollectionRequest,
  ifMatch?: string | null
): Promise<ResponseWithMeta<RerunCollection>> {
  return requestWithMeta<RerunCollection>(`/api/v1/rerun-collections/${id}`, {
    body,
    method: 'PUT',
    headers: ifMatch ? { 'If-Match': ifMatch } : undefined
  });
}

export function deleteRerunCollection(id: number): Promise<void> {
  return request<void>(`/api/v1/rerun-collections/${id}`, { method: 'DELETE' });
}

export function messageFromRerunCollectionError(
  error: unknown,
  fallback = 'Unable to load rerun collections'
): string {
  if (error instanceof ApiError) {
    return error.detail ?? error.message;
  }

  if (error instanceof Error) {
    return error.message;
  }

  return fallback;
}
