import { Router } from "express";
import { z } from "zod";
import { validate } from "../middleware/validate.js";
import { activityService } from "../services/activity.js";
import { assertBoard, assertCompanyAccess } from "./authz.js";
import { issueService } from "../services/index.js";
import { sanitizeRecord } from "../redaction.js";
const createActivitySchema = z.object({
    actorType: z.enum(["agent", "user", "system"]).optional().default("system"),
    actorId: z.string().min(1),
    action: z.string().min(1),
    entityType: z.string().min(1),
    entityId: z.string().min(1),
    agentId: z.string().uuid().optional().nullable(),
    details: z.record(z.unknown()).optional().nullable(),
});
export function activityRoutes(db) {
    const router = Router();
    const svc = activityService(db);
    const issueSvc = issueService(db);
    function stringQueryParam(value) {
        return typeof value === "string" && value.trim() ? value : undefined;
    }
    function actorTypeQueryParam(value) {
        return value === "agent" || value === "user" || value === "system" ? value : undefined;
    }
    async function resolveIssueByRef(rawId) {
        if (/^[A-Z]+-\d+$/i.test(rawId)) {
            return issueSvc.getByIdentifier(rawId);
        }
        return issueSvc.getById(rawId);
    }
    router.get("/orgs/:orgId/activity", async (req, res) => {
        const orgId = req.params.orgId;
        assertCompanyAccess(req, orgId);
        const filters = {
            orgId,
            agentId: stringQueryParam(req.query.agentId),
            userId: stringQueryParam(req.query.userId),
            actorType: actorTypeQueryParam(req.query.actorType),
            actorId: stringQueryParam(req.query.actorId),
            entityType: stringQueryParam(req.query.entityType),
            entityId: stringQueryParam(req.query.entityId),
        };
        const result = await svc.list(filters);
        res.json(result);
    });
    router.post("/orgs/:orgId/activity", validate(createActivitySchema), async (req, res) => {
        assertBoard(req);
        const orgId = req.params.orgId;
        const event = await svc.create({
            orgId,
            ...req.body,
            details: req.body.details ? sanitizeRecord(req.body.details) : null,
        });
        res.status(201).json(event);
    });
    router.get("/issues/:id/activity", async (req, res) => {
        const rawId = req.params.id;
        const issue = await resolveIssueByRef(rawId);
        if (!issue) {
            res.status(404).json({ error: "Issue not found" });
            return;
        }
        assertCompanyAccess(req, issue.orgId);
        const result = await svc.forIssue(issue.id);
        res.json(result);
    });
    router.get("/issues/:id/runs", async (req, res) => {
        const rawId = req.params.id;
        const issue = await resolveIssueByRef(rawId);
        if (!issue) {
            res.status(404).json({ error: "Issue not found" });
            return;
        }
        assertCompanyAccess(req, issue.orgId);
        const result = await svc.runsForIssue(issue.orgId, issue.id);
        res.json(result);
    });
    router.get("/heartbeat-runs/:runId/issues", async (req, res) => {
        const runId = req.params.runId;
        const result = await svc.issuesForRun(runId);
        res.json(result);
    });
    return router;
}
//# sourceMappingURL=activity.js.map