/**
 * OwnSets Service - General setup data
 * type: 404=general, 402=db, 408=connection
 */
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class OwnsetsService {
  constructor(private prisma: PrismaService) {}

  async findByType(type: number) {
    return this.prisma.ownSet.findMany({
      where: { type },
      orderBy: { id: 'asc' },
    });
  }

  async findOne(type: number, id: number) {
    const row = await this.prisma.ownSet.findUnique({
      where: { id_type: { id, type } },
    });
    if (!row) throw new NotFoundException(`OwnSet type=${type} id=${id} not found`);
    return row;
  }

  async upsert(type: number, id: number, data: Record<string, unknown>) {
    const allowed = [
      'name', 'userid', 'txt1', 'txt2', 'txt3', 'txt4', 'txt5', 'txt6',
      'txt7', 'txt8', 'txt9', 'txt10', 'txt11', 'txt12', 'txt13', 'txt14', 'txt15',
      'i1', 'i2', 'i3', 'i4', 'i5', 'i6', 'i7', 'i8', 'i9', 'i10', 'i11', 'i12',
      'i39', 'i40', 'i41', 'i42', 'i43', 'i44', 'i45', 'i48',
      'x18', 'x19', 'x48',
    ];
    const updateData: Record<string, unknown> = {};
    for (const k of allowed) {
      if (data[k] !== undefined) updateData[k] = data[k];
    }
    return this.prisma.ownSet.upsert({
      where: { id_type: { id, type } },
      create: { id, type, ...updateData } as { id: number; type: number } & Record<string, unknown>,
      update: updateData,
    });
  }
}
