import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { SafeZone } from './entities/safe-zone.entity'; import { SafeZoneDto, SafeZoneSettingsDto } from './dto/safe-zone.dto'; import { User } from '../users/entities/user.entity'; @Injectable() export class SafeZonesService { constructor( @InjectRepository(SafeZone) private zoneRepo: Repository, @InjectRepository(User) private userRepo: Repository, ) {} async findAll(userId: number) { const zones = await this.zoneRepo.find({ where: { userId }, order: { Created: 'DESC' }, }); return zones.map((z) => ({ Id: z.Id, Name: z.Name, Location: { Lat: z.Lat, Lng: z.Lng }, Radius: z.Radius, WifiName: z.WifiName, Created: z.Created, })); } async create(userId: number, dto: SafeZoneDto) { const zone = this.zoneRepo.create({ Name: dto.Name || '', Lat: dto.Location?.Lat || 0, Lng: dto.Location?.Lng || 0, Radius: dto.Radius || 100, WifiName: dto.WifiName, userId, }); const saved = await this.zoneRepo.save(zone); return { Id: saved.Id, Name: saved.Name, Location: { Lat: saved.Lat, Lng: saved.Lng }, Radius: saved.Radius, WifiName: saved.WifiName, Created: saved.Created, }; } async update(userId: number, id: number, dto: SafeZoneDto) { const zone = await this.zoneRepo.findOne({ where: { Id: id, userId } }); if (!zone) throw new NotFoundException('Safe zone not found'); if (dto.Name !== undefined) zone.Name = dto.Name; if (dto.Location) { if (dto.Location.Lat !== undefined) zone.Lat = dto.Location.Lat; if (dto.Location.Lng !== undefined) zone.Lng = dto.Location.Lng; } if (dto.Radius !== undefined) zone.Radius = dto.Radius; if (dto.WifiName !== undefined) zone.WifiName = dto.WifiName; await this.zoneRepo.save(zone); return { Id: zone.Id, Name: zone.Name, Location: { Lat: zone.Lat, Lng: zone.Lng }, Radius: zone.Radius, WifiName: zone.WifiName, Created: zone.Created, }; } async delete(userId: number, id: number): Promise { const result = await this.zoneRepo.delete({ Id: id, userId }); if (result.affected === 0) throw new NotFoundException('Safe zone not found'); } async getSettings(userId: number) { const user = await this.userRepo.findOne({ where: { id: userId } }); if (!user) throw new NotFoundException('User not found'); return { Enabled: user.SafeZoneEnabled, LastUpdate: new Date(user.Created as any).toISOString(), }; } async updateSettings(userId: number, dto: SafeZoneSettingsDto) { const user = await this.userRepo.findOne({ where: { id: userId } }); if (!user) throw new NotFoundException('User not found'); user.SafeZoneEnabled = dto.Enabled; await this.userRepo.save(user); return { Enabled: user.SafeZoneEnabled, LastUpdate: new Date().toISOString(), }; } async getDefaultRadius() { return { Radius: 100 }; } }