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

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

    const schema = z.object({
      name: z.string().min(1, "Name is required"),
      notes: z.string().optional(),
      typeId: z.string().min(1, "Type ID is required"),
      companyId: z.string().min(1, "Company ID is required"),
      fields: z.array(
        z.object({
          fieldId: z.string(),
          value: z.string(),
        }),
      ),
      subCredentials: z
        .record(
          z.string(),
          z.array(
            z.object({
              name: z.string().min(1, "Sub-credential name is required"),
              fields: z.array(
                z.object({
                  fieldId: z.string(),
                  value: z.string(),
                }),
              ),
            }),
          ),
        )
        .optional(),
    });

    const data = schema.parse(body);

    const credential = await credentials.create(data);

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