package usecase import ( "fmt" "time" "users_management/m/model/dto/req" "users_management/m/model/entity" "users_management/m/repository" "github.com/go-playground/validator/v10" "github.com/google/uuid" ) type DeviceUseCase interface { CreateDevice(device req.DeviceDTO) error GetAllDevices() ([]entity.Device, error) GetByID(id uuid.UUID) (entity.Device, error) UpdateDevice(id uuid.UUID, device req.UpdateDeviceDTO) error } type deviceUseCase struct { deviceRepo repository.DevicesRepo validate *validator.Validate } func NewDeviceUseCase(deviceRepo repository.DevicesRepo) DeviceUseCase { return &deviceUseCase{ deviceRepo: deviceRepo, validate: validator.New(), } } func (u *deviceUseCase) CreateDevice(device req.DeviceDTO) error { err := u.validate.Struct(device) if err != nil { return fmt.Errorf("validation error: %w", err) } newDevice := entity.Device{ ID: uuid.New(), DeviceCode: device.DeviceCode, DeviceType: entity.DeviceType(device.DeviceType), Longitude: device.Longitude, Latitude: device.Latitude, PortAmount: device.PortAmount, Status: entity.DeviceStatus(device.Status), CreatedAt: time.Now(), UpdatedAt: time.Now(), } return u.deviceRepo.Post(newDevice) } func (u *deviceUseCase) GetAllDevices() ([]entity.Device, error) { devices, err := u.deviceRepo.GetAll() if err != nil { return devices, err } return devices, nil } func (u *deviceUseCase) GetByID(id uuid.UUID) (entity.Device, error) { device, err := u.deviceRepo.GetByID(id) if err != nil { return device, err } return device, nil } func (u *deviceUseCase) UpdateDevice(id uuid.UUID, device req.UpdateDeviceDTO) error { err := u.validate.Struct(device) if err != nil { return fmt.Errorf("validation error: %w", err) } updates := map[string]interface{}{} if device.DeviceCode != nil { updates["DeviceCode"] = *device.DeviceCode } if device.DeviceType != nil { updates["DeviceType"] = *device.DeviceType } if device.Longitude != nil { updates["Longitude"] = *device.Longitude } if device.Latitude != nil { updates["Latitude"] = *device.Latitude } if device.PortAmount != nil { updates["PortAmount"] = *device.PortAmount } if len(updates) == 0 { return fmt.Errorf("no update data") } updates["UpdatedAt"] = time.Now() return u.deviceRepo.Update(id, updates) }