/**
 * Items Service
 *
 * Replaces: GetItem, GetItemp, GetToItem, GetFrItem from OracleDM
 * Table: items (Inventory items)
 */
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class ItemsService {
  constructor(private prisma: PrismaService) {}

  /**
   * Get item by mg_no, mt_no
   * Maps to: GetItem(mg, mt, a) where a=0 for mtr_code=1, a=1 for mtr_code=2
   */
  async getItem(mgNo: string, mtNo: string, mtrCode: number = 1) {
    return this.prisma.item.findUnique({
      where: {
        mgNo_mtNo_mtrCode: {
          mgNo,
          mtNo,
          mtrCode,
        },
      },
    });
  }

  /**
   * Get all items (optionally filtered)
   * mtUp: get children of parent (for tree navigation)
   */
  async findAll(mgNo?: string, mtNo?: string, mtUp?: string) {
    const where: { mgNo?: string; mtNo?: string; mtUp?: string | null } = {};
    if (mgNo) where.mgNo = mgNo;
    if (mtNo) where.mtNo = mtNo;
    if (mtUp !== undefined) where.mtUp = mtUp || null;
    return this.prisma.item.findMany({
      where,
      orderBy: [{ mgNo: 'asc' }, { mtNo: 'asc' }],
    });
  }
}
