import { json } from '@sveltejs/kit';
import pool from '$lib/server/database';
import type { RequestHandler } from './$types';

// PUT handler
export const PUT: RequestHandler = async ({ params, request }) => {
    const { id } = params;
    const { x, y, width, height } = await request.json();

    const tumerPosition = [Math.round(x), Math.round(y), Math.round(x + width), Math.round(y + height)];

    try {
        await pool.query(
            'UPDATE public."TumerDataset" SET "TumerPosition" = $1 WHERE "Index" = $2',
            [tumerPosition, id]
        );
        return json({ success: true });
    } catch (err) {
        console.error(`API Error updating rectangle ${id}:`, err);
        return json({ error: 'Failed to update rectangle' }, { status: 500 });
    }
};

// DELETE handler
export const DELETE: RequestHandler = async ({ params }) => {
    const { id } = params;
    try {
        await pool.query('DELETE FROM public."TumerDataset" WHERE "Index" = $1', [id]);
        return json({ success: true });
    } catch (err) {
        console.error(`API Error deleting rectangle ${id}:`, err);
        return json({ error: 'Failed to delete rectangle' }, { status: 500 });
    }
};