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

// GET handler (existing)
export const GET: RequestHandler = async ({ params }) => {
  const { refIndex } = params;
  try {
    const result = await pool.query<{ Index: number; TumerPosition: number[] }>(
      'SELECT "Index", "TumerPosition" FROM public."TumerDataset" WHERE "IndexRef" = $1',
      [refIndex]
    );
    const rectangles: Rectangle[] = result.rows.map(row => {
        const [x1, y1, x2, y2] = row.TumerPosition;
        const x = Math.min(x1, x2);
        const y = Math.min(y1, y2);
        const width = Math.abs(x2 - x1);
        const height = Math.abs(y2 - y1);
        return { id: row.Index, x, y, width, height };
    });
    return json(rectangles);
  } catch (err) {
    console.error(`API Error fetching rectangles for ${refIndex}:`, err);
    return json({ error: 'Failed to fetch rectangles' }, { status: 500 });
  }
};

// POST handler (new)
export const POST: RequestHandler = async ({ params, request }) => {
    const { refIndex } = 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 {
        const result = await pool.query(
            `INSERT INTO public."TumerDataset" ("IndexRef", "DataNumber", "TumerPosition", "LocationFile")
             SELECT $1, "DataNumber", $2, "LocationFile" FROM public."TumerDatasetRef" WHERE "Index" = $1
             RETURNING "Index"`,
            [refIndex, tumerPosition]
        );
        return json({ id: result.rows[0].Index }, { status: 201 });
    } catch (err) {
        console.error('API Error creating rectangle:', err);
        return json({ error: 'Failed to create rectangle' }, { status: 500 });
    }
};