import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class RegionsService {
  constructor(private readonly prisma: PrismaService) {}

  async tree() {
    const regions = await this.prisma.region.findMany({ orderBy: [{ level: 'asc' }, { code: 'asc' }] });
    const map = new Map<string, any>();
    const roots: any[] = [];

    regions.forEach((region) => map.set(region.id, { ...region, children: [] }));
    map.forEach((region) => {
      if (region.parentId && map.has(region.parentId)) {
        map.get(region.parentId).children.push(region);
      } else {
        roots.push(region);
      }
    });

    return roots;
  }

  create(dto: any) {
    return this.prisma.region.create({
      data: {
        code: dto.code,
        name: dto.name,
        level: Number(dto.level),
        parentId: dto.parentId,
        longitude: dto.longitude,
        latitude: dto.latitude,
      },
    });
  }

  update(id: string, dto: any) {
    return this.prisma.region.update({
      where: { id },
      data: {
        code: dto.code,
        name: dto.name,
        level: dto.level === undefined ? undefined : Number(dto.level),
        parentId: dto.parentId,
        longitude: dto.longitude,
        latitude: dto.latitude,
      },
    });
  }
}
