import { buildContract } from '@jig-software/trest-core';
import { z } from 'zod';
import { Config } from '../schemas';

export const ConfigCache = Config.omit({
  privateKey: true,
  publicKey: true,
}).extend({
  privateKey: z.object({}).passthrough(),
  publicKey: z.object({}).passthrough(),
});
export type ConfigCache = z.infer<typeof ConfigCache>;

export const UpdateConfigDto = Config.pick({
  publicKey: true,
  privateKey: true,
  cookieSecret: true,
  acceptRegistration: true,
  acceptedHosts: true,
  autoActivateUser: true,
  emailServer: true,
  totpLifeTime: true,
  passwordRequirements: true,
  lockPeriods: true,
})
  .extend({
    emailServer: z.object({
      host: z.string(),
      port: z.number(),
      secure: z.boolean(),
      auth: z
        .object({
          user: z.string(),
          pass: z.string(),
        })
        .optional(),
      tls: z
        .object({
          serverName: z.string(),
          rejectUnauthorized: z.boolean(),
        })
        .partial()
        .optional(),
    }),
  })
  .partial({});
export type UpdateConfigDto = z.infer<typeof UpdateConfigDto>;

export const configContract = buildContract((c) =>
  c
    .prefix('config')
    .parse((p) =>
      p.error.text(500).error.text(400).error.text(401).error.text(403),
    )
    .endpoints({
      getConfig: (e) =>
        e.method('GET').parse((p) => p.success.object(200, ConfigCache)),
      updateConfig: (e) =>
        e
          .method('PATCH')
          .prepare((p) => p.body.json(UpdateConfigDto))
          .parse((p) => p.success.object(200, Config)),
    }),
);
