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

export const CreateClientDto = Client.pick({
  name: true,
  clientId: true,
  url: true,
}).extend({
  adminUsername: z.string(),
  adminPassword: z.string(),
  email: z.string(),
});
export type CreateClientDto = z.infer<typeof CreateClientDto>;

export const ActivateClientDto = z.object({
  email: z.string(),
  secret: z.string(),
});
export type ActivateClientDto = z.infer<typeof ActivateClientDto>;

export const UpdateClientDto = Client.pick({
  url: true,
})
  .extend({
    secret: z.string(),
  })
  .partial();
export type UpdateClientDto = z.infer<typeof UpdateClientDto>;

export const clientContract = buildContract((c) =>
  c
    .prefix('clients')
    .parse((p) =>
      p.error.text(500).error.text(400).error.text(401).error.text(403),
    )
    .endpoints({
      createClient: (e) =>
        e
          .method('POST')
          .prepare((p) => p.body.json(CreateClientDto))
          .parse((p) => p.success.object(201, Client)),
      activateClient: (e) =>
        e
          .method('PATCH')
          .path('activate/:clientId')
          .prepare((p) => p.param('clientId').body.json(ActivateClientDto))
          .parse((p) => p.success.object(200, Client)),
      getClients: (e) =>
        e.method('GET').parse((p) => p.success.object(200, z.array(Client))),
      getClient: (e) =>
        e
          .method('GET')
          .path(':clientId')
          .prepare((p) => p.param('clientId'))
          .parse((p) => p.success.object(200, Client)),
      updateClient: (e) =>
        e
          .method('PATCH')
          .path(':clientId')
          .prepare((p) => p.param('clientId').body.json(UpdateClientDto))
          .parse((p) => p.success.object(200, Client)),
      deleteClient: (e) =>
        e
          .method('DELETE')
          .path(':clientId')
          .prepare((p) => p.param('clientId'))
          .parse((p) => p.success.object(200, Client)),
    }),
);
