import { api } from '$lib/api';

const BASE_PATH = '/v1/a76/audit-log/files';

export interface AuditFileBreadcrumb {
	path: string;
	display_name: string;
}

export interface AuditFolderItem {
	path: string;
	display_name: string;
}

export interface AuditFileItem {
	path: string;
	display_name: string;
	size: number;
	last_modified?: string | null;
}

export interface AuditFileListResponse {
	current_path: string;
	display_path: string;
	breadcrumbs: AuditFileBreadcrumb[];
	folders: AuditFolderItem[];
	files: AuditFileItem[];
	next_token?: string | null;
}

export const AuditFilesAPI = {
	list: async (
		companyId: number,
		params?: {
			path?: string;
			continuation_token?: string;
			max_keys?: number;
		}
	): Promise<AuditFileListResponse> => {
		const query = new URLSearchParams();
		query.set('company_id', String(companyId));
		if (params?.path) query.set('path', params.path);
		if (params?.continuation_token) query.set('continuation_token', params.continuation_token);
		if (params?.max_keys) query.set('max_keys', String(params.max_keys));

		const qs = query.toString();
		const endpoint = `${BASE_PATH}?${qs}`;
		const response = await api.get<AuditFileListResponse>(endpoint);
		if (response.error || !response.data) {
			throw new Error(response.error || 'Failed to list tenant files');
		}
		return response.data;
	},

	downloadBlob: (companyId: number, path: string) =>
		api.getBlob(
			`${BASE_PATH}/download?company_id=${companyId}&path=${encodeURIComponent(path)}`
		)
};
