import { FastifyRequest, FastifyReply } from 'fastify';
import { CanvasApiEndpoint } from '../../entities/CanvasApiEndpoint';

interface CreateEndpointBody {
    name: string;
    method: string;
    path: string;
    description?: string;
    user?: any;
}

interface UpdateEndpointBody {
    name?: string;
    method?: string;
    path?: string;
    description?: string;
}

export class CanvasApiEndpointController {
    async getAll(request: FastifyRequest, reply: FastifyReply) {
        const endpoints = await request.em.find(CanvasApiEndpoint, {});
        return reply.send(endpoints);
    }

    async create(request: FastifyRequest<{ Body: CreateEndpointBody }>, reply: FastifyReply) {
        const { name, method, path, description, user } = request.body;
        if (!name || !method || !path) {
            return reply.status(400).send({ error: 'name, method, and path are required' });
        }
        const endpoint = new CanvasApiEndpoint();
        endpoint.name = name;
        endpoint.method = method;
        endpoint.path = path;
        endpoint.description = description;
        endpoint.user = user;
        await request.em.persistAndFlush(endpoint);
        return reply.send(endpoint);
    }

    async delete(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
        const id = Number(request.params.id);
        if (!id) return reply.status(400).send({ error: 'Missing id' });
        const endpoint = await request.em.findOne(CanvasApiEndpoint, { id });
        if (!endpoint) return reply.status(404).send({ error: 'Not found' });
        await request.em.removeAndFlush(endpoint);
        return reply.send({ success: true });
    }

    async update(request: FastifyRequest<{ Params: { id: string }; Body: UpdateEndpointBody }>, reply: FastifyReply) {
        const id = Number(request.params.id);
        if (!id) return reply.status(400).send({ error: 'Missing id' });
        const endpoint = await request.em.findOne(CanvasApiEndpoint, { id });
        if (!endpoint) return reply.status(404).send({ error: 'Not found' });
        const { name, method, path, description } = request.body;
        if (name) endpoint.name = name;
        if (method) endpoint.method = method;
        if (path) endpoint.path = path.replace(/^\/api\/v1/, '');
        if (description !== undefined) endpoint.description = description;
        await request.em.persistAndFlush(endpoint);
        return reply.send(endpoint);
    }
} 