import { auditHttp } from './audit.http'

export type AuditChange = {
	field: string
	from: unknown
	to: unknown
}

export type AuditLogCommandItem = {
	id: string
	createdAt: string
	deletedAt: string | null
	entityName: string
	payload: unknown | null
	changes: AuditChange[]
	queryMethod: 'INSERT' | 'UPDATE' | 'DELETE' | string
	auditLog: unknown | null
}

export type AuditLogExtensionItem = {
	id?: string
	createdAt: string
	entityName: string
	queryMethod: 'INSERT' | 'UPDATE' | 'DELETE' | string
	user: {
		id: string
		name: {
			am: string
			en: string
		}
		email: string
		userId?: string
		username?: string
		sessionId?: string
		employeeId?: string
		positionId?: string
		employeePositionId?: string
	}
	changes?: AuditChange[]
}

export type Paginated<T> = {
	count: number
	items: T[]
}

export type AuditListQuery = {
	skip?: number
	take?: number
	orderBy?: string
}

export type AuditContext = {
	unitId?: string
	organizationId?: string
}

type ParamValue = string | number | boolean | null | undefined

function toParams<T extends Record<string, ParamValue>>(q?: T) {
	if (!q) return undefined

	const params = new URLSearchParams()

	Object.entries(q).forEach(([k, v]) => {
		if (v === undefined || v === null) return
		if (typeof v === 'string' && v.trim() === '') return
		params.set(k, String(v))
	})

	return params
}

export async function listAuditLogCommandsByModule(
	moduleKey: string,
	query?: AuditListQuery,
	context?: AuditContext,
) {
	const { data } = await auditHttp.get<Paginated<AuditLogCommandItem>>(
		`/audit-log-commands/all/${encodeURIComponent(moduleKey)}`,
		{
			params: toParams(query),
			headers: {
				...(context?.unitId
					? { 'x-current-unit-id': context.unitId }
					: {}),
				...(context?.organizationId
					? { 'x-current-organization-id': context.organizationId }
					: {}),
			},
		},
	)
	return data
}

export async function listAuditLogExtensions(
	endpoint: string = '/audit-log-extensions/audit/unitAdmin',
	query?: AuditListQuery,
) {
	const { data } = await auditHttp.get<Paginated<AuditLogExtensionItem>>(
		endpoint,
		{
			params: toParams(query),
		},
	)
	return data
}
