import { CrudService } from '../services/CrudService.js';
import { safeError } from '../utils/errorHandler.js';

export class CrudController {
    static async getMany(req, res) {
        const { table } = req.params;
        const page = parseInt(req.query.page) || 0;
        const limit = Math.min(100, parseInt(req.query.limit) || 100);
        const offset = page * limit;
        try {
            const rows = await CrudService.getMany(table, limit, offset);
            res.json(rows);
        } catch (error) { safeError(res, error); }
    }

    static async create(req, res) {
        const { table } = req.params;
        try {
            const record = await CrudService.create(table, req.body);
            res.status(201).json(record);
        } catch (error) { safeError(res, error); }
    }

    static async update(req, res) {
        const { table, id } = req.params;
        try {
            await CrudService.update(table, id, req.body);
            res.json({ success: true });
        } catch (error) { safeError(res, error); }
    }

    static async remove(req, res) {
        const { table, id } = req.params;
        try {
            await CrudService.remove(table, id);
            res.json({ success: true });
        } catch (error) { safeError(res, error); }
    }
}
