import { PROGRAM_VERSION } from "../constants.js";
import { Label, logger } from "../logger.js";
import { createIndexer, deleteIndexer, getIndexerById, indexerCreateSchema, indexerTestSchema, indexerUpdateSchema, listAllIndexers, testExistingIndexer, testNewIndexer, updateIndexer, } from "../services/indexerService.js";
import { authorize } from "../utils/authUtils.js";
// Helper function to parse and validate ID from route params
async function parseIdParam(idParam, reply) {
    const id = parseInt(idParam, 10);
    if (isNaN(id) || id <= 0) {
        await reply.code(400).send({
            code: "VALIDATION_ERROR",
            message: "Invalid indexer ID",
        });
        return false;
    }
    return id;
}
/**
 * Prowlarr Integration API Routes
 * Base path: /api/indexer/v1
 */
export async function indexerApiPlugin(app) {
    /**
     * Indexer management status for Prowlarr integration
     */
    app.get("/status", async (request, reply) => {
        if (!(await authorize(request, reply)))
            return;
        const statusResponse = {
            version: PROGRAM_VERSION,
            appName: "cross-seed",
        };
        return reply.code(200).send(statusResponse);
    });
    /**
     * List all indexers
     */
    app.get("", async (request, reply) => {
        if (!(await authorize(request, reply)))
            return;
        const indexers = await listAllIndexers();
        return reply.code(200).send(indexers);
    });
    /**
     * Get single indexer by ID
     */
    app.get("/:id", async (request, reply) => {
        if (!(await authorize(request, reply)))
            return;
        const id = await parseIdParam(request.params.id, reply);
        if (!id)
            return;
        const result = await getIndexerById(id);
        if (result.isOk()) {
            return reply.code(200).send(result.unwrap());
        }
        const err = result.unwrapErr();
        return reply.code(404).send(err);
    });
    /**
     * Create new indexer
     */
    app.post("", async (request, reply) => {
        if (!(await authorize(request, reply)))
            return;
        const validation = indexerCreateSchema.safeParse(request.body);
        if (!validation.success) {
            return reply.code(400).send({
                code: "VALIDATION_ERROR",
                message: validation.error.message,
            });
        }
        const indexer = await createIndexer(validation.data);
        return reply.code(200).send(indexer);
    });
    /**
     * Update existing indexer
     */
    app.put("/:id", async (request, reply) => {
        if (!(await authorize(request, reply)))
            return;
        const id = await parseIdParam(request.params.id, reply);
        if (!id)
            return;
        // Ensure body ID matches URL ID
        if (request.body.id !== id) {
            return reply.code(400).send({
                code: "VALIDATION_ERROR",
                message: "ID in request body must match URL parameter",
            });
        }
        const validation = indexerUpdateSchema.safeParse(request.body);
        if (!validation.success) {
            return reply.code(400).send({
                code: "VALIDATION_ERROR",
                message: validation.error.message,
            });
        }
        const result = await updateIndexer(validation.data);
        if (result.isOk()) {
            return reply.code(200).send(result.unwrap());
        }
        const err = result.unwrapErr();
        return reply.code(404).send(err);
    });
    /**
     * Delete indexer
     */
    app.delete("/:id", async (request, reply) => {
        if (!(await authorize(request, reply)))
            return;
        const id = await parseIdParam(request.params.id, reply);
        if (!id)
            return;
        const result = await deleteIndexer(id);
        if (result.isOk()) {
            return reply.code(200).send(result.unwrap());
        }
        const err = result.unwrapErr();
        return reply.code(404).send(err);
    });
    /**
     * Test indexer connection
     */
    app.post("/test", async (request, reply) => {
        if (!(await authorize(request, reply)))
            return;
        let result;
        if (request.body.id) {
            // Test existing indexer
            result = await testExistingIndexer(request.body.id);
        }
        else {
            // Test new indexer configuration
            const validation = indexerTestSchema.safeParse(request.body);
            if (!validation.success) {
                return reply.code(400).send({
                    code: "VALIDATION_ERROR",
                    message: validation.error.message,
                });
            }
            result = await testNewIndexer(validation.data);
        }
        if (result.isOk()) {
            const success = result.unwrap();
            return reply.code(200).send({
                ok: true,
                message: success.message,
            });
        }
        const err = result.unwrapErr();
        if (err.code === "INDEXER_NOT_FOUND") {
            return reply.code(404).send(err);
        }
        logger.warn({
            label: Label.SERVER,
            message: `Connection test failed: ${err.message}`,
        });
        return reply.code(200).send({
            ok: false,
            code: err.code,
            message: err.message,
        });
    });
}
//# sourceMappingURL=indexerApi.js.map