// #region ReportsApi [C:3] [TYPE Module] [SEMANTICS report, api, search, filter, query]
// @BRIEF Reports API client — list/detail retrieval, query-string building, error normalization.
// @LAYER API
// @RELATION DEPENDS_ON -> [ApiModule]
// @PRE Shared API wrapper is configured for the current frontend auth/session context.
// @POST Report list and detail helpers return backend payloads or normalized UI-safe errors.

import { api } from '../api';

// #region reportApiTypes [C:1] [TYPE Block] [SEMANTICS types, reports]
interface ReportQueryOptions {
	page?: number;
	page_size?: number;
	task_types?: string[];
	statuses?: string[];
	time_from?: string;
	time_to?: string;
	search?: string;
	sort_by?: string;
	sort_order?: string;
}

interface NormalizedError {
	message: string;
	code: string;
	retryable: boolean;
}
// #endregion reportApiTypes

// #region buildReportQueryString [C:2] [TYPE Function] [SEMANTICS report, query, params]
// @BRIEF Build query string for reports list endpoint from filter options.
// @PRE options is an object with optional report query fields.
// @POST Returns URL query string without leading '?'.
export function buildReportQueryString(options: ReportQueryOptions = {}): string {
	const params = new URLSearchParams();

	if (options.page != null) params.append('page', String(options.page));
	if (options.page_size != null) params.append('page_size', String(options.page_size));

	if (Array.isArray(options.task_types) && options.task_types.length > 0) {
		params.append('task_types', options.task_types.join(','));
	}
	if (Array.isArray(options.statuses) && options.statuses.length > 0) {
		params.append('statuses', options.statuses.join(','));
	}

	if (options.time_from) params.append('time_from', options.time_from);
	if (options.time_to) params.append('time_to', options.time_to);
	if (options.search) params.append('search', options.search);
	if (options.sort_by) params.append('sort_by', options.sort_by);
	if (options.sort_order) params.append('sort_order', options.sort_order);

	return params.toString();
}
// #endregion buildReportQueryString

// #region normalizeApiError [C:2] [TYPE Function] [SEMANTICS report, error, normalization]
// @BRIEF Convert unknown API exceptions into deterministic UI-consumable error objects.
// @PRE error may be Error/string/object.
// @POST Returns structured error object with message, code, retryable flag.
export function normalizeApiError(error: unknown): NormalizedError {
	const message =
		(error && typeof (error as Error).message === 'string' && (error as Error).message) ||
		(typeof error === 'string' && error) ||
		'Failed to load reports';

	return {
		message,
		code: 'REPORTS_API_ERROR',
		retryable: true,
	};
}
// #endregion normalizeApiError

// #region getReports [C:3] [TYPE Function] [SEMANTICS report, list, fetch]
// @BRIEF Fetch unified report list using the shared API wrapper.
// @PRE Valid auth context for protected endpoint.
// @POST Returns parsed payload or throws normalized error.
// @SIDE_EFFECT Performs authenticated GET request through api.fetchApi.
// @RELATION DEPENDS_ON -> [ApiModule.fetchApi]
export async function getReports<T = unknown>(options: ReportQueryOptions = {}): Promise<T> {
	try {
		const query = buildReportQueryString(options);
		return await api.fetchApi<T>(`/reports${query ? `?${query}` : ''}`);
	} catch (error) {
		throw normalizeApiError(error);
	}
}
// #endregion getReports

// #region getReportDetail [C:3] [TYPE Function] [SEMANTICS report, detail, fetch]
// @BRIEF Fetch one report detail by report_id.
// @PRE reportId is non-empty string; valid auth context.
// @POST Returns parsed detail payload or throws normalized error.
// @SIDE_EFFECT Performs authenticated GET request through api.fetchApi.
// @RELATION DEPENDS_ON -> [ApiModule.fetchApi]
export async function getReportDetail<T = unknown>(reportId: string): Promise<T> {
	try {
		return await api.fetchApi<T>(`/reports/${reportId}`);
	} catch (error) {
		throw normalizeApiError(error);
	}
}
// #endregion getReportDetail
// #endregion ReportsApi
