import { command, form, getRequestEvent, query } from '$app/server';
import { createDeviceSchema, type Device } from '$lib/schema/device';
import { error } from '@sveltejs/kit';
import z from 'zod';

export const listDevices = query(async (): Promise<Device[]> => {
	const { locals } = getRequestEvent();

	const response = await locals.api.get(`/devices`);

	if (!response.ok) error(500, 'An unkown error occurred');

	const deviceResult = await response.json();
	return deviceResult.items;
});

export const createDevice = form(createDeviceSchema, async (data): Promise<Device> => {
	const { locals } = getRequestEvent();

	const response = await locals.api.post(`/devices`, data);

	if (!response.ok) error(500, 'An unknown error occurred');

	return await response.json();
});

export const regenerateDeviceApiKey = command(z.string(), async (deviceId): Promise<Device> => {
	const { locals } = getRequestEvent();

	const response = await locals.api.get(`/devices/${deviceId}/regenerate`);

	if (!response.ok) error(500, 'An unknown error occurred');

	return await response.json();
});

export const deleteDevice = command(z.string(), async (deviceId): Promise<void> => {
	const { locals } = getRequestEvent();

	const response = await locals.api.delete(`/devices/${deviceId}`);

	if (!response.ok) error(500, 'An unknown error occurred');
});
