// import { registry } from "../../infrastructure/openapi/registry";
// import { z } from "zod";
// import { ErrorResponseSchema } from "../../infrastructure/openapi/security";
// import { createTaskSchema } from "./task.validation";

// const TaskResponseSchema = registry.register(
//   "TaskResponse",
//   z.object({
//     success: z.boolean().default(true),
//     statusCode: z.number().default(201),
//     message: z.string(),
//     data: z.any().optional(),
//   })
// );

// registry.registerPath({
//   method: "post",
//   path: "/tasks/create-task",
//   summary: "Create a new task (Admin only)",
//   tags: ["Tasks"],
//   security: [{ bearerAuth: [] }],
//   request: {
//     body: {
//       content: {
//         "application/json": {
//           schema: createTaskSchema.shape.body,
//         },
//       },
//     },
//   },
//   responses: {
//     201: {
//       description: "Task created successfully",
//       content: { "application/json": { schema: TaskResponseSchema } },
//     },
//     400: {
//       description: "Validation failed or employee not in department",
//       content: { "application/json": { schema: ErrorResponseSchema } },
//     },
//     401: {
//       description: "Unauthorized",
//       content: { "application/json": { schema: ErrorResponseSchema } },
//     },
//     404: {
//       description: "Client / Service / Department not found",
//       content: { "application/json": { schema: ErrorResponseSchema } },
//     },
//   },
// });

import { registry } from "../../infrastructure/openapi/registry";
import { z } from "zod";
import { ErrorResponseSchema } from "../../infrastructure/openapi/security";
import {
  createTaskSchema,
  getTasksSchema,
  taskIdParamSchema,
  adminGetTasksSchema,
  adminUpdateTaskSchema,
  managerDecisionSchema,
} from "./task.validation";

const TaskResponseSchema = registry.register(
  "TaskResponse",
  z.object({
    success: z.boolean().default(true),
    statusCode: z.number().default(200),
    message: z.string().optional(),
    data: z.any().optional(),
  }),
);

const TaskListResponseSchema = registry.register(
  "TaskListResponse",
  z.object({
    success: z.boolean().default(true),
    statusCode: z.number().default(200),
    message: z.string().optional(),
    data: z.array(z.any()).optional(),
    meta: z
      .object({
        total: z.number(),
        page: z.number(),
        limit: z.number(),
      })
      .optional(),
  }),
);

// ============================================================
// CLIENT ROUTES
// ============================================================

registry.registerPath({
  method: "post",
  path: "/tasks/create-task",
  summary: "Create a new task with documents (Client only)",
  tags: ["Tasks - Client"],
  security: [{ bearerAuth: [] }],
  request: {
    body: {
      content: {
        "multipart/form-data": {
          schema: createTaskSchema.shape.body.extend({
            // file fields are keyed by serviceDocumentId, uploaded as multipart files
          }),
        },
      },
    },
  },
  responses: {
    201: {
      description: "Task created successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description:
        "Validation failed, missing required documents, or client profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Service not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/rejections",
  summary:
    "Get all client tasks with rejected documents/approvals (Client only)",
  tags: ["Tasks - Client"],
  security: [{ bearerAuth: [] }],
  responses: {
    200: {
      description: "Rejected tasks fetched successfully",
      content: { "application/json": { schema: TaskListResponseSchema } },
    },
    400: {
      description: "Client profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks",
  summary: "Get paginated list of tasks (Client only)",
  tags: ["Tasks - Client"],
  security: [{ bearerAuth: [] }],
  request: {
    query: getTasksSchema.shape.query.unwrap(),
  },
  responses: {
    200: {
      description: "Tasks fetched successfully",
      content: { "application/json": { schema: TaskListResponseSchema } },
    },
    400: {
      description: "Client profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/{taskId}/rejections",
  summary:
    "Get rejected documents and manager rejection remarks for a task (Client only)",
  tags: ["Tasks - Client"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
  },
  responses: {
    200: {
      description: "Rejections fetched successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Client profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/{taskId}",
  summary: "Get a single task by ID (Client only)",
  tags: ["Tasks - Client"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
  },
  responses: {
    200: {
      description: "Task fetched successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Client profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "put",
  path: "/tasks/{taskId}",
  summary:
    "Update a task, add new documents, or remove existing ones (Client only)",
  tags: ["Tasks - Client"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
    body: {
      content: {
        "multipart/form-data": {
          schema: z.object({
            title: z.string().optional(),
            description: z.string().optional(),
            dueDate: z.string().optional(),
            status: z.string().optional(),
            removeDocumentIds: z
              .string()
              .optional()
              .describe(
                "JSON array string or comma-separated document IDs to remove",
              ),
          }),
        },
      },
    },
  },
  responses: {
    200: {
      description: "Task updated successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Client profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "delete",
  path: "/tasks/{taskId}",
  summary: "Delete a task and its documents (Client only)",
  tags: ["Tasks - Client"],
  security: [{ bearerAuth: [] }],
  request: {
    params: taskIdParamSchema.shape.params,
  },
  responses: {
    200: {
      description: "Task deleted successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Client profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "patch",
  path: "/tasks/{taskId}/client-approve",
  summary: "Client approves or rejects a task pending client approval",
  tags: ["Tasks - Client"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
    body: {
      content: {
        "application/json": {
          schema: z.object({
            status: z.enum(["APPROVED", "REJECTED"]),
            remarks: z
              .string()
              .optional()
              .describe("Required when status is REJECTED"),
          }),
        },
      },
    },
  },
  responses: {
    200: {
      description: "Task decision recorded successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Remarks required to reject, or client profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found or not awaiting client approval",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

// ============================================================
// EMPLOYEE ROUTES
// ============================================================

registry.registerPath({
  method: "get",
  path: "/tasks/employee/tasks",
  summary: "Get paginated list of tasks assigned to the logged-in employee",
  tags: ["Tasks - Employee"],
  security: [{ bearerAuth: [] }],
  request: {
    query: z.object({
      page: z.string().optional(),
      limit: z.string().optional(),
      search: z.string().optional(),
      status: z.string().optional(),
      priority: z.string().optional(),
    }),
  },
  responses: {
    200: {
      description: "Employee tasks fetched successfully",
      content: { "application/json": { schema: TaskListResponseSchema } },
    },
    400: {
      description: "Employee profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/employee/tasks/{taskId}",
  summary: "Get a single task assigned to the logged-in employee",
  tags: ["Tasks - Employee"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
  },
  responses: {
    200: {
      description: "Task fetched successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Employee profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "patch",
  path: "/tasks/{taskId}/approval",
  summary: "Employee verifies or rejects one or more uploaded documents",
  tags: ["Tasks - Employee"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
    body: {
      content: {
        "application/json": {
          schema: z.object({
            documentIds: z.array(z.string()),
            status: z.enum(["VERIFIED", "REJECTED"]),
            remarks: z.string().optional(),
          }),
        },
      },
    },
  },
  responses: {
    200: {
      description: "Document verification recorded successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Employee profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "patch",
  path: "/tasks/{taskId}/approve",
  summary: "Employee approves a task after all documents are verified",
  tags: ["Tasks - Employee"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
    body: {
      content: {
        "application/json": {
          schema: z.object({ remarks: z.string().optional() }),
        },
      },
    },
  },
  responses: {
    200: {
      description: "Task approved and moved to manager approval",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description:
        "Employee profile not found, or all documents not yet verified",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

// ============================================================
// MANAGER ROUTES
// ============================================================

registry.registerPath({
  method: "get",
  path: "/tasks/manager/tasks",
  summary:
    "Get paginated list of tasks for the logged-in manager (Manager/Admin only)",
  tags: ["Tasks - Manager"],
  security: [{ bearerAuth: [] }],
  request: {
    query: z.object({
      page: z.string().optional(),
      limit: z.string().optional(),
      search: z.string().optional(),
      status: z.string().optional(),
      priority: z.string().optional(),
    }),
  },
  responses: {
    200: {
      description: "Manager tasks fetched successfully",
      content: { "application/json": { schema: TaskListResponseSchema } },
    },
    400: {
      description: "Manager profile not found or access denied",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "patch",
  path: "/tasks/manager/{taskId}/approve",
  summary: "Manager approves or rejects a task pending manager approval",
  tags: ["Tasks - Manager"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
    body: {
      content: {
        "application/json": { schema: managerDecisionSchema.shape.body },
      },
    },
  },
  responses: {
    200: {
      description: "Manager decision recorded successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Remarks required to reject, or manager profile not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found or not awaiting manager approval",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/manager/tasks/{taskId}",
  summary: "Get a single task for the logged-in manager (Manager/Admin only)",
  tags: ["Tasks - Manager"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
  },
  responses: {
    200: {
      description: "Task fetched successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Manager profile not found or access denied",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

// ============================================================
// ADMIN ROUTES
// ============================================================

registry.registerPath({
  method: "get",
  path: "/tasks/admin/stats",
  summary: "Get pending/completed/rejected task counts (Admin only)",
  tags: ["Tasks - Admin"],
  security: [{ bearerAuth: [] }],
  responses: {
    200: {
      description: "Task stats fetched successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Admin organization not found or access denied",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/admin/all",
  summary: "Get paginated list of all org tasks with filters (Admin only)",
  tags: ["Tasks - Admin"],
  security: [{ bearerAuth: [] }],
  request: {
    query: adminGetTasksSchema.shape.query.unwrap(),
  },
  responses: {
    200: {
      description: "Tasks fetched successfully",
      content: { "application/json": { schema: TaskListResponseSchema } },
    },
    400: {
      description: "Admin organization not found or access denied",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/admin/clients/active",
  summary:
    "Get paginated list of active/invited clients in the org (Admin only)",
  tags: ["Tasks - Admin"],
  security: [{ bearerAuth: [] }],
  request: {
    query: z.object({
      page: z.string().optional(),
      limit: z.string().optional(),
      search: z.string().optional(),
    }),
  },
  responses: {
    200: {
      description: "Active clients fetched successfully",
      content: { "application/json": { schema: TaskListResponseSchema } },
    },
    400: {
      description: "Admin organization not found or access denied",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/admin/employees/active",
  summary: "Get list of active employees in the org (Admin only)",
  tags: ["Tasks - Admin"],
  security: [{ bearerAuth: [] }],
  responses: {
    200: {
      description: "Active employees fetched successfully",
      content: { "application/json": { schema: TaskListResponseSchema } },
    },
    400: {
      description: "Admin organization not found or access denied",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/admin/departments/{departmentId}/employees",
  summary: "Get active employees in a specific department (Admin only)",
  tags: ["Tasks - Admin"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({
      departmentId: z.string().describe("Department ID"),
    }),
    query: z.object({ search: z.string().optional() }),
  },
  responses: {
    200: {
      description: "Department employees fetched successfully",
      content: { "application/json": { schema: TaskListResponseSchema } },
    },
    400: {
      description: "Admin organization not found or access denied",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "post",
  path: "/tasks/admin/create",
  summary:
    "Create a task on behalf of a client, with optional documents (Admin only)",
  tags: ["Tasks - Admin"],
  security: [{ bearerAuth: [] }],
  request: {
    body: {
      content: {
        "multipart/form-data": {
          schema: z.object({
            clientId: z.string(),
            serviceId: z.string(),
            departmentId: z.string().optional(),
            assignedEmployeeId: z.string().optional(),
            title: z.string(),
            description: z.string().optional(),
            dueDate: z.string().optional(),
            priority: z.enum(["LOW", "MEDIUM", "HIGH", "URGENT"]).optional(),
          }),
        },
      },
    },
  },
  responses: {
    201: {
      description: "Task created successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description:
        "Validation failed, employee not active, or admin organization not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Client or service not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "get",
  path: "/tasks/admin/{taskId}",
  summary: "Get a single task by ID (Admin only)",
  tags: ["Tasks - Admin"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
  },
  responses: {
    200: {
      description: "Task fetched successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Admin organization not found or access denied",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "patch",
  path: "/tasks/admin/{taskId}",
  summary:
    "Update a task's status/assignment/details. Marking as COMPLETED auto-generates an invoice and Stripe payment link, and emails the client (Admin only)",
  tags: ["Tasks - Admin"],
  security: [{ bearerAuth: [] }],
  request: {
    params: adminUpdateTaskSchema.shape.params,
    body: {
      content: {
        "application/json": { schema: adminUpdateTaskSchema.shape.body },
      },
    },
  },
  responses: {
    200: {
      description: "Task updated successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description:
        "Validation failed, employee not active in org, or admin organization not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});

registry.registerPath({
  method: "delete",
  path: "/tasks/admin/{taskId}",
  summary:
    "Delete a task along with its documents, approvals, and invoice (Admin only)",
  tags: ["Tasks - Admin"],
  security: [{ bearerAuth: [] }],
  request: {
    params: z.object({ taskId: z.string().describe("Task ID") }),
  },
  responses: {
    200: {
      description: "Task deleted successfully",
      content: { "application/json": { schema: TaskResponseSchema } },
    },
    400: {
      description: "Admin organization not found or access denied",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    401: {
      description: "Unauthorized",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
    404: {
      description: "Task not found",
      content: { "application/json": { schema: ErrorResponseSchema } },
    },
  },
});
