import { db } from "../db.ts";
import { requireAuth } from "../auth.ts";

export const handleStorage = async (req: Request, key: string): Promise<Response> => {
    if (!key) {
        return Response.json({ error: "Storage key required" }, { status: 400 });
    }

    const auth = await requireAuth(req);
    if (auth instanceof Response) return auth;
    const { userId } = auth;

    if (req.method === "GET") {
        const [row] = await db`
            SELECT value FROM storage WHERE user_id = ${userId} AND key = ${key}
        `;
        if (!row) return Response.json({});
        try {
            return Response.json(JSON.parse(row.value as string));
        } catch {
            return Response.json({});
        }
    }

    if (req.method === "POST") {
        let body: unknown;
        try {
            body = await req.json();
        } catch {
            return Response.json({ error: "Invalid JSON" }, { status: 400 });
        }

        if (body === null || body === undefined) {
            return Response.json({ error: "Body required" }, { status: 400 });
        }

        const value = JSON.stringify(body);
        await db`
            INSERT INTO storage (user_id, key, value, updated_at)
            VALUES (${userId}, ${key}, ${value}, datetime('now'))
            ON CONFLICT(user_id, key)
            DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
        `;
        return Response.json({ ok: true });
    }

    return Response.json({ error: "Method not allowed" }, { status: 405 });
};
