import { UUidWithPrefix } from "#components/Ausweis/types.js";
import { authorizationMiddleware } from "#lib/middleware/authorization.js";
import { prisma } from "#lib/server/prisma.js";
import { defineApiRoute } from "astro-typesafe-api/server";
import { ObjektSchema } from "src/generated/zod/index.js";
import { z } from "zod";

export const PUT = defineApiRoute({
	input: ObjektSchema.omit({
		id: true,
		uid: true,
		benutzer_id: true,
		erstellungsdatum: true
	}),
	output: z.object({
		uid: UUidWithPrefix
	}),
	middleware: authorizationMiddleware,
	async fetch(input, context, user) {
		const objekt = await prisma.objekt.create({
			data: {
				...input,
				benutzer: {
					connect: {
						id: user.id
					}
				}
			},
		})

		return {
			uid: objekt.uid
		}
	},
})

export const GET = defineApiRoute({
	input: z.object({
		limit: z.number()
	}),
	output: z.array(ObjektSchema),
	middleware: authorizationMiddleware,
	async fetch(input, context, transfer) {
		const objekte = await prisma.objekt.findMany({
			take: input.limit,
			where: {
				benutzer: {
					id: transfer.id
				}
			}
		})

		return objekte
	},
})