import { createRoute } from "../../modules/api-utils/createRoute";
import { credentials } from "../../managers/credentials";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { z } from "zod";

/* POST /v1/credential/credentials/:id/sub-credentials */
export default createRoute(
  "post",
  ["/credentials/:id/sub-credentials"],

  async (c) => {
    const parentId = c.req.param("id");
    const body = await c.req.json();

    const schema = z.object({
      fieldId: z.string().min(1, "Field ID is required"),
      name: z.string().min(1, "Name is required"),
      fields: z.array(
        z.object({
          fieldId: z.string(),
          value: z.string(),
        }),
      ),
    });

    const data = schema.parse(body);

    const subCredential = await credentials.addSubCredential(
      parentId,
      data.fieldId,
      {
        name: data.name,
        fields: data.fields,
      },
    );

    const response = apiResponse.created(
      "Sub-Credential Created Successfully!",
      subCredential.toJson(),
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({
    permissions: ["credential.fetch", "credential.sub_credentials.create"],
  }),
);
