/**
 * Glinfo Service - INF lookup tables
 * INF_TYPE: 1=branches, 2=currency, 3=mandoub, 4=mrklfe, 5=shahen, 6=saller, etc.
 */
import { Injectable, ConflictException, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class GlinfoService {
  constructor(private prisma: PrismaService) {}

  async findByType(infType: number) {
    return this.prisma.glinfo.findMany({
      where: { infType },
      orderBy: { infId: 'asc' },
    });
  }

  async create(infType: number, infId: number, infName?: string) {
    const existing = await this.prisma.glinfo.findUnique({
      where: { infId_infType: { infId, infType } },
    });
    if (existing) throw new ConflictException(`Glinfo infId=${infId} infType=${infType} exists`);
    return this.prisma.glinfo.create({
      data: { infId, infType, infName: infName ?? null },
    });
  }

  async update(infType: number, infId: number, infName?: string) {
    const existing = await this.prisma.glinfo.findUnique({
      where: { infId_infType: { infId, infType } },
    });
    if (!existing) throw new NotFoundException(`Glinfo infId=${infId} infType=${infType} not found`);
    return this.prisma.glinfo.update({
      where: { infId_infType: { infId, infType } },
      data: { infName: infName ?? existing.infName },
    });
  }

  async delete(infType: number, infId: number) {
    try {
      return await this.prisma.glinfo.delete({
        where: { infId_infType: { infId, infType } },
      });
    } catch {
      throw new NotFoundException(`Glinfo infId=${infId} infType=${infType} not found`);
    }
  }
}
