import { A, buildContract } from '@jig-software/trest-core';
import { z } from 'zod';

// Schema to be completed
export const RocketChatWebHookPayload = z
  .object({
    text: z.string(),
    user_name: z.string(),
    channel_id: z.string(),
    message_id: z.string(),
    isEdited: z.boolean().optional(),
    tmid: z.string().optional(),
  })
  .passthrough();
export type RocketChatWebHookPayload = z.infer<typeof RocketChatWebHookPayload>;

export const RocketChatAttachment = z.object({
  text: z.string().optional(),
  collapsed: z.string().optional(),
  color: z.string().optional(),
  actions: z
    .array(
      z.object({
        type: z.enum(['button']),
        text: z.string().optional(),
        msg: z.string().optional(),
        msg_in_chat_window: z.boolean().optional(),
      }),
    )
    .optional(),
  type: z.string().optional(), // file
  format: z.string().optional(),
  title: z.string().optional(),
  title_link: z.string().optional(),
  title_link_download: z.boolean().optional(),
});
export type RocketChatAttachment = z.infer<typeof RocketChatAttachment>;

export const RocketChatWebHookReturn = z.object({
  text: z.string().optional(),
  attachments: z.array(RocketChatAttachment).optional(),
});
export type RocketChatWebHookReturn = z.infer<typeof RocketChatWebHookReturn>;

export const webHookContract = buildContract((c) =>
  c.prefix('/web-hooks').endpoints({
    rocketChatWebHook: (e) =>
      e
        .method('POST')
        .path('/rocket-chat')
        .prepare((p) =>
          p.body.json(RocketChatWebHookPayload).annotate<[payload: A]>(),
        )
        .parse((p) => p.success.object(200, RocketChatWebHookReturn)),
  }),
);
