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 */
export default createRoute(
  "patch",
  ["/credentials/:id"],

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

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

    const data = schema.parse(body);

    if (data.fields) {
      await credential.validateAndUpdateFields(data.fields);
    }

    if (data.name !== undefined || data.notes !== undefined) {
      await credential.update({
        ...(data.name !== undefined && { name: data.name }),
        ...(data.notes !== undefined && { notes: data.notes }),
      });
    }

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