import { ApiError, request, type Manga, type Page } from './client';
import type { Chapter } from './chapters';

/**
 * Tagged union returned by `GET /v1/me/uploads`. The discriminant lives
 * on the `kind` field; pattern-match on it before accessing the rest.
 */
export type UploadEntry =
    | { kind: 'manga'; manga: Manga; created_at: string }
    | {
          kind: 'chapter';
          manga_id: string;
          manga_title: string;
          manga_cover_image_path: string | null;
          chapter: Chapter;
          created_at: string;
      };

export type UploadsPage = {
    items: UploadEntry[];
    page: Page;
};

export async function listMyUploads(
    opts: { limit?: number } = {}
): Promise<UploadsPage> {
    const params = new URLSearchParams();
    if (opts.limit != null) params.set('limit', String(opts.limit));
    const qs = params.toString();
    return request<UploadsPage>(`/v1/me/uploads${qs ? `?${qs}` : ''}`);
}

export async function listMyUploadsOrEmpty(): Promise<UploadsPage> {
    try {
        return await listMyUploads();
    } catch (e) {
        if (e instanceof ApiError && e.status === 401) {
            return { items: [], page: { limit: 50, offset: 0, total: null } };
        }
        throw e;
    }
}
