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

/* /v1/credential-type/:id */
export default createRoute(
  "patch",
  ["/:id"],

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

    const fieldSchema: z.ZodType<any> = z.lazy(() =>
      z.object({
        id: z.string(),
        name: z.string(),
        required: z.boolean(),
        secure: z.boolean(),
        valueType: z.enum(Object.values(ValueType)),
        subFields: z.array(fieldSchema).optional(),
      }),
    );

    const schema = z.object({
      name: z.string().optional(),
      permissionScope: z.string().optional(),
      icon: z.string().optional(),
      fields: z.array(fieldSchema).optional(),
    });

    const data = schema.parse(body);

    await credentialType.update(data as any);

    const response = apiResponse.successful(
      "Credential Type Updated Successfully!",
      credentialType.toJson(),
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["credential_type.update"] }),
);
