import { A, buildContract } from '@jig-software/trest-core';
import { objectId } from '@jig-software/zod-bson';
import { z } from 'zod';
import { LeaveCancellation, WorkDay } from '../schemas';

export const LeaveCancellationInit = LeaveCancellation.pick({
  applyRemarks: true,
  appliedBy: true,
}).extend({
  workDays: z.array(WorkDay).min(1),
});
export type LeaveCancellationInit = z.infer<typeof LeaveCancellationInit>;

export const LeaveCancellationApprovalInit = LeaveCancellation.pick({
  approvedBy: true,
  approveRemarks: true,
});
export type LeaveCancellationApprovalInit = z.infer<
  typeof LeaveCancellationApprovalInit
>;

export const LeaveCancellationRejectionInit = LeaveCancellation.pick({
  rejectedBy: true,
  rejectRemarks: true,
});
export type LeaveCancellationRejectionInit = z.infer<
  typeof LeaveCancellationRejectionInit
>;

export const LeaveCancellationCancellationInit = LeaveCancellation.pick({
  canceledBy: true,
  cancelRemarks: true,
});
export type LeaveCancellationCancellationInit = z.infer<
  typeof LeaveCancellationCancellationInit
>;

export const leaveCancellationContract = buildContract((c) =>
  c
    .prefix('/leave-cancellations')
    .parse((p) => p.error.text(400))
    .endpoints({
      createLeaveCancellation: (e) =>
        e
          .method('POST')
          .prepare((p) =>
            p.body.json(LeaveCancellationInit).annotate<[init: A]>(),
          )
          .parse((p) => p.success.object(201, LeaveCancellation)),
      getLeaveCancellations: (e) =>
        e
          .method('GET')
          .parse((p) => p.success.object(200, z.array(LeaveCancellation))),
      approveLeaveCancellation: (e) =>
        e
          .method('POST')
          .path('/:_id/approval')
          .prepare((p) =>
            p
              .param('_id', objectId())
              .body.json(LeaveCancellationApprovalInit)
              .annotate<[_id: A, init: A]>(),
          )
          .parse((p) => p.success.object(200, LeaveCancellation)),
      rejectLeaveCancellation: (e) =>
        e
          .method('POST')
          .path('/:_id/rejection')
          .prepare((p) =>
            p
              .param('_id', objectId())
              .body.json(LeaveCancellationRejectionInit)
              .annotate<[_id: A, init: A]>(),
          )
          .parse((p) => p.success.object(200, LeaveCancellation)),
      cannelLeaveCancellation: (e) =>
        e
          .method('POST')
          .path('/:_id/cancellation')
          .prepare((p) =>
            p
              .param('_id', objectId())
              .body.json(LeaveCancellationCancellationInit)
              .annotate<[_id: A, init: A]>(),
          )
          .parse((p) => p.success.object(200, LeaveCancellation)),
    }),
);
