/**
 * {{PASCAL_NAME}} Routes
 *
 * Auto-generated by SPFN CLI
 */

import { createApp } from '@spfn/core/route';
import { Transactional } from '@spfn/core/db';
import { {{REPO_NAME}} } from '@/repositories/{{KEBAB_NAME}}.repository.js';
import {
    list{{PASCAL_NAME}}Contract,
    create{{PASCAL_NAME}}Contract,
} from '@/contracts/{{KEBAB_NAME}}.js';

const app = createApp();

/**
 * GET /{{ENTITY_NAME}}
 * List {{PASCAL_NAME}} items
 */
app.bind(list{{PASCAL_NAME}}Contract, async (c) =>
{
    const { limit = 20, offset = 0 } = c.query;

    const items = await {{REPO_NAME}}.findMany({ limit, offset });

    return c.json({
        items: items.map((item) => ({
            id: item.id,
            name: item.name,
            description: item.description,
            createdAt: item.createdAt.toISOString(),
            updatedAt: item.updatedAt.toISOString(),
        })),
        limit,
        offset,
    });
});

/**
 * POST /{{ENTITY_NAME}}
 * Create new {{PASCAL_NAME}}
 */
app.bind(create{{PASCAL_NAME}}Contract, [Transactional()], async (c) =>
{
    const body = await c.data();

    const item = await {{REPO_NAME}}.create({
        name: body.name,
        description: body.description,
    });

    return c.json(
        {
            id: item.id,
            name: item.name,
            description: item.description,
            createdAt: item.createdAt.toISOString(),
            updatedAt: item.updatedAt.toISOString(),
        },
        201
    );
});

export default app;