import { api } from "@/lib/api/client";

export type Device = {
	id: string;
	serialNumber: string;
	name: string;
	ipAddress: string;
	port: number;
	location: string | null;
	connectionMode: string;
	lastSeenAt: string | null;
	isActive: boolean;
	createdAt: string;
	updatedAt: string;
};

export type CreateDeviceInput = {
	serialNumber: string;
	name: string;
	ipAddress: string;
	port?: number;
	location?: string;
};

export type UpdateDeviceInput = {
	name?: string;
	ipAddress?: string;
	port?: number;
	location?: string;
	isActive?: boolean;
};

export type DeviceHealth = {
	deviceId: string;
	name: string;
	ipAddress: string;
	port: number;
	lastSeenAt: string | null;
	online?: boolean;
	realtimeActive?: boolean;
	deviceLogCount?: number;
	dbLogCount?: number;
	message?: string;
};

export type DeviceLog = {
	id: string;
	employeeId: string | null;
	employeeCode: string;
	employeeName: string | null;
	punchedAt: string;
	punchType: string;
	verifyMode: string;
	source: string;
	deviceSerial: string;
	isMapped: boolean;
};

export function getDevices() {
	return api.get<{ items: Device[] }>("/devices");
}

export function createDevice(data: CreateDeviceInput) {
	return api.post<Device>("/devices", data);
}

export function updateDevice(id: string, data: UpdateDeviceInput) {
	return api.patch<Device>(`/devices/${id}`, data);
}

export function deactivateDevice(id: string) {
	return api.delete<Device>(`/devices/${id}`);
}

export function syncDevice(id: string) {
	return api.post<{
		deviceId: string;
		imported: number;
		skipped: number;
		fetched: number;
	}>(`/devices/${id}/sync`);
}

export function getDeviceHealth(id: string) {
	return api.get<DeviceHealth>(`/devices/${id}/health`);
}

export function getDeviceLogs(
	id: string,
	params: { limit?: number; offset?: number; date?: string; hours?: number } = {},
) {
	const search = new URLSearchParams();
	if (params.limit != null) search.set("limit", String(params.limit));
	if (params.offset != null) search.set("offset", String(params.offset));
	if (params.date) search.set("date", params.date);
	if (params.hours != null) search.set("hours", String(params.hours));
	const query = search.toString();
	return api.get<{ total: number; items: DeviceLog[] }>(
		`/devices/${id}/logs${query ? `?${query}` : ""}`,
	);
}
