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

export const CreatePrivilegeDto = Privilege.pick({
  grantedTo: true,
  privilege: true,
});
export type CreatePrivilegeDto = z.infer<typeof CreatePrivilegeDto>;

export const RevokePrivilegeDto = Privilege.pick({
  grantedTo: true,
  privilege: true,
});
export type RevokePrivilegeDto = z.infer<typeof RevokePrivilegeDto>;

export const RemovePrivilegeResult = z.object({
  revoked: z.number().int(),
});
export type RemovePrivilegeResult = z.infer<typeof RemovePrivilegeResult>;

export const privilegeContract = buildContract((c) =>
  c
    .prefix('privileges')
    .parse((p) =>
      p.error.text(500).error.text(400).error.text(401).error.text(403),
    )
    .endpoints({
      addPrivilege: (e) =>
        e
          .method('POST')
          .path(':clientId')
          .prepare((p) => p.param('clientId').body.json(CreatePrivilegeDto))
          .parse((p) => p.success.object(201, Privilege)),
      removePrivilege: (e) =>
        e
          .method('DELETE')
          .path(':clientId')
          .prepare((p) => p.param('clientId').body.json(RevokePrivilegeDto))
          .parse((p) => p.success.object(200, RemovePrivilegeResult)),
    }),
);
