"use server";

import { authOptions } from "@/app/auth";
import type { ApiError, ApiResponse, Device } from "@/lib/backend-types";
import { checkSession } from "@/utils/session";
import { handleApiResponse } from "@/utils/tryCatch";
import { getServerSession } from "next-auth";
import { revalidatePath } from "next/cache";

type GetDevicesProps = {
	query?: string;
	offset?: number;
	limit?: number;
	page?: number;
	sortBy?: string;
	status?: string;
};
export async function getDevices({ query, offset, limit }: GetDevicesProps) {
	const session = await checkSession();
	const response = await fetch(
		`${process.env.SARLINK_API_BASE_URL}/api/devices/?name=${query}&offset=${offset}&limit=${limit}`,
		{
			method: "GET",
			headers: {
				"Content-Type": "application/json",
				Authorization: `Token ${session?.apiToken}`,
			},
		},
	);

	return handleApiResponse<ApiResponse<Device>>(response, "getDevices");
}

export async function getDevice({ deviceId }: { deviceId: string }) {
	const session = await checkSession();
	const response = await fetch(
		`${process.env.SARLINK_API_BASE_URL}/api/devices/${deviceId}/`,
		{
			method: "GET",
			headers: {
				"Content-Type": "application/json",
				Authorization: `Token ${session?.apiToken}`,
			},
		},
	);
	return handleApiResponse<Device>(response, "getDevice");
}

export async function addDevice({
	name,
	mac,
}: {
	name: string;
	mac: string;
}) {
	type SingleDevice = Pick<Device, "name" | "mac">;
	const session = await getServerSession(authOptions);
	const response = await fetch(
		`${process.env.SARLINK_API_BASE_URL}/api/devices/`,
		{
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				Authorization: `Token ${session?.apiToken}`,
			},
			body: JSON.stringify({
				name: name,
				mac: mac,
				registered: true,
			}),
		},
	);
	revalidatePath("/devices");
	return handleApiResponse<SingleDevice>(response, "addDevice");
}

export async function blockDevice({
	deviceId,
	reason_for_blocking,
	blocked_by,
}: {
	deviceId: string;
	reason_for_blocking: string;
	blocked_by: "ADMIN" | "PARENT";
}) {
	const session = await getServerSession(authOptions);
	const response = await fetch(
		`${process.env.SARLINK_API_BASE_URL}/api/devices/${deviceId}/block/`,
		{
			method: "PUT",
			headers: {
				"Content-Type": "application/json",
				Authorization: `Token ${session?.apiToken}`,
			},
			body: JSON.stringify({
				blocked: true,
				reason_for_blocking: session?.user?.is_superuser
					? reason_for_blocking
					: "Blocked by parent",
				blocked_by: session?.user?.is_superuser ? "ADMIN" : "PARENT",
			}),
		},
	);
	return handleApiResponse<Device>(response, "blockDevice");
}