import { Hono } from "hono/tiny";
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";

/* /v1/credential/:id/fields */
export default createRoute(
  "put",
  ["/credentials/:id/fields"],

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

    const schema = z.object({
      fields: z.array(
        z.object({
          fieldId: z.string(),
          value: z.string(),
        }),
      ),
    });

    const data = schema.parse(body);

    await credential.validateAndUpdateFields(data.fields);

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