import { createRoute } from "../../../../modules/api-utils/createRoute";
import { unifiSites } from "../../../../managers/unifiSites";
import { apiResponse } from "../../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../../middleware/authorization";
import { z } from "zod";

/* POST /v1/unifi/site/:id/wifi/:wlanId/ppsk */
export default createRoute(
  "post",
  ["/site/:id/wifi/:wlanId/ppsk"],
  async (c) => {
    const site = await unifiSites.fetch(c.req.param("id"));
    const wlanId = c.req.param("wlanId");

    const body = await c.req.json();
    const schema = z
      .object({
        key: z.string().min(8, "PSK must be at least 8 characters"),
        name: z.string().min(1, "Name is required"),
        mac: z.string().optional(),
        vlanId: z.number().optional(),
      })
      .strict();

    const parsed = schema.parse(body);
    const ppsks = await unifiSites.createPrivatePSK(
      site.siteId,
      wlanId,
      parsed,
    );

    const response = apiResponse.created(
      "UniFi Private PSK Created Successfully!",
      ppsks,
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({
    permissions: [
      "unifi.access",
      "unifi.site.wifi",
      "unifi.site.wifi.ppsk",
      "unifi.site.wifi.ppsk.create",
    ],
  }),
);
