import { MovementType, Prisma } from "@/generated/prisma/client"
import { paginate } from "@/lib/paginate"
import prisma from "@/lib/prisma"
import { CreateMovementFormType } from "@/lib/schemas/movement.schemas"
import { Movement } from "@/lib/types"

import { getAuthenticatedUserId } from "./auth.service"

type MovementListResult = {
  id: string
  type: MovementType
  quantity: number
  createdAt: Date
  item: { name: string } | null
  asset: { serialNumber: string } | null
  recipient: { firstName: string; lastName: string } | null
}

export const MovementService = {
  findAll: async ({ page, pageSize }: { page?: number; pageSize?: number }) => {
    return paginate<MovementListResult>({
      model: prisma.movement,
      page,
      pageSize,
      orderBy: {
        createdAt: "desc",
      },
      select: {
        id: true,
        type: true,
        quantity: true,
        createdAt: true,
        item: {
          select: {
            name: true,
          },
        },
        asset: {
          select: {
            serialNumber: true,
          },
        },
        recipient: {
          select: {
            firstName: true,
            lastName: true,
          },
        },
      },
    })
  },
  create: async (data: CreateMovementFormType): Promise<Movement> => {
    return await prisma.movement.create({
      data: {
        ...data,
        userId: await getAuthenticatedUserId(),
      },
    })
  },

  update: async (
    id: string,
    data: Prisma.MovementUpdateInput,
  ): Promise<Movement> => {
    return await prisma.movement.update({
      where: { id },
      data,
    })
  },

  findAllByItemId: async (itemId: string): Promise<Movement[]> => {
    return await prisma.movement.findMany({
      where: { itemId },
    })
  },
}
