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 */
export default createRoute(
  "post",
  ["/"],

  async (c) => {
    const body = await c.req.json();

    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().min(1, "Name is required"),
      permissionScope: z.string().min(1, "Permission scope is required"),
      icon: z.string().optional(),
      fields: z.array(fieldSchema),
    });

    const data = schema.parse(body);

    const credentialType = await credentialTypes.create(data as any);

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