import { NextResponse } from "next/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { resolveOrganizationScopeFilter } from "@open-mercato/core/modules/directory/utils/organizationScopeFilter";
import { UserTask } from "../../data/entities.js";
import {
  workflowsTag,
  userTaskListQuerySchema,
  userTaskListResponseSchema,
  workflowErrorSchema
} from "../openapi.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
const metadata = {
  requireAuth: true,
  requireFeatures: ["workflows.tasks.view"]
};
async function GET(request) {
  try {
    const container = await createRequestContainer();
    const em = container.resolve("em");
    const auth = await getAuthFromRequest(request);
    if (!auth) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    const scope = await resolveOrganizationScopeForRequest({ container, auth, request });
    const tenantId = auth.tenantId;
    const orgFilter = resolveOrganizationScopeFilter(scope, auth);
    if (!tenantId) {
      return NextResponse.json(
        { error: "Missing tenant context" },
        { status: 400 }
      );
    }
    const { searchParams } = new URL(request.url);
    const status = searchParams.get("status");
    const assignedTo = searchParams.get("assignedTo");
    const workflowInstanceId = searchParams.get("workflowInstanceId");
    const overdue = searchParams.get("overdue") === "true";
    const myTasks = searchParams.get("myTasks") === "true";
    const limit = parseInt(searchParams.get("limit") || "50");
    const offset = parseInt(searchParams.get("offset") || "0");
    const where = {
      tenantId,
      ...orgFilter.where
    };
    if (status) {
      const statusValues = status.split(",").map((s) => s.trim()).filter(Boolean);
      if (statusValues.length === 1) {
        where.status = statusValues[0];
      } else if (statusValues.length > 1) {
        where.status = { $in: statusValues };
      }
    }
    if (assignedTo) {
      where.assignedTo = assignedTo;
    }
    if (workflowInstanceId) {
      where.workflowInstanceId = workflowInstanceId;
    }
    if (overdue) {
      where.dueDate = { $lt: /* @__PURE__ */ new Date() };
      where.status = { $in: ["PENDING", "IN_PROGRESS"] };
    }
    if (myTasks) {
      where.$or = [
        { assignedTo: auth.sub },
        { assignedToRoles: { $overlap: auth.roles || [] } }
      ];
    }
    const [tasks, total] = await em.findAndCount(
      UserTask,
      where,
      {
        orderBy: { createdAt: "DESC" },
        limit,
        offset
      }
    );
    return NextResponse.json({
      data: tasks,
      pagination: {
        total,
        limit,
        offset,
        hasMore: offset + tasks.length < total
      }
    });
  } catch (error) {
    logger.error("Error listing user tasks", { err: error });
    return NextResponse.json(
      {
        error: "Failed to list user tasks",
        details: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
}
const openApi = {
  tag: workflowsTag,
  summary: "User task management",
  methods: {
    GET: {
      summary: "List user tasks",
      description: "Returns paginated list of user tasks with optional filtering by status, assignee, workflow instance, overdue, and myTasks flags.",
      query: userTaskListQuerySchema,
      responses: [
        { status: 200, description: "User tasks list with pagination", schema: userTaskListResponseSchema }
      ],
      errors: [
        { status: 400, description: "Invalid query parameters or missing tenant context", schema: workflowErrorSchema },
        { status: 401, description: "Unauthorized", schema: workflowErrorSchema },
        { status: 500, description: "Internal server error", schema: workflowErrorSchema }
      ]
    }
  }
};
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
