import { GpsFixType, LocateMode, UtilityType } from '@prisma/client';
import { Type } from 'class-transformer';
import {
  ArrayMaxSize,
  ArrayMinSize,
  IsArray,
  IsDateString,
  IsEnum,
  IsInt,
  IsNotEmpty,
  IsNumber,
  IsOptional,
  IsString,
  Max,
  MaxLength,
  Min,
  ValidateNested,
} from 'class-validator';

export class MqttPointDto {
  @IsNumber()
  @Min(-90)
  @Max(90)
  lat: number;

  @IsNumber()
  @Min(-180)
  @Max(180)
  lng: number;

  @IsOptional()
  @IsNumber()
  alt?: number;

  @IsOptional()
  @IsEnum(GpsFixType)
  fix?: GpsFixType;

  @IsOptional()
  @IsNumber()
  @Min(0)
  hAcc?: number;

  @IsOptional()
  @IsNumber()
  @Min(0)
  depth?: number;

  @IsOptional()
  @IsEnum(UtilityType)
  utility?: UtilityType;

  @IsOptional()
  @IsInt()
  seq?: number;

  // GPS quality
  @IsOptional()
  @IsNumber()
  @Min(0)
  vAcc?: number;

  @IsOptional()
  @IsInt()
  @Min(0)
  sats?: number;

  @IsOptional()
  @IsNumber()
  @Min(0)
  hdop?: number;

  // Locator receiver telemetry
  @IsOptional()
  @IsInt()
  @Min(0)
  freqHz?: number;

  @IsOptional()
  @IsNumber()
  @Min(0)
  currentMa?: number;

  @IsOptional()
  @IsNumber()
  signalDb?: number;

  @IsOptional()
  @IsNumber()
  gainDb?: number;

  @IsOptional()
  @IsEnum(LocateMode)
  mode?: LocateMode;

  @IsOptional()
  @IsNumber()
  phaseDeg?: number;

  @IsOptional()
  @IsNumber()
  @Min(0)
  @Max(360)
  compassDeg?: number;

  @IsOptional()
  @IsNumber()
  @Min(0)
  @Max(100)
  distortionPct?: number;

  @IsDateString()
  ts: string;
}

export class MqttPointsMessageDto {
  // Job is resolved by jobId when present, else by (device org, ticket)
  @IsOptional()
  @IsString()
  jobId?: string;

  @IsOptional()
  @IsString()
  @MaxLength(64)
  ticket?: string;

  // Locator receiver serial number; the publisher (MQTT credential) may be a
  // phone/gateway relaying for one or more locators. Auto-registered on first sight.
  @IsOptional()
  @IsString()
  @MaxLength(64)
  serial?: string;

  @IsArray()
  @ArrayMinSize(1)
  @ArrayMaxSize(500)
  @ValidateNested({ each: true })
  @Type(() => MqttPointDto)
  points: MqttPointDto[];
}

// Single-reading log entry for a locator that publishes directly (or is
// relayed) to devices/<serial>/log — the serial comes from the topic itself,
// so identity is job-anchored rather than publisher-credential-anchored.
export class MqttLogMessageDto extends MqttPointDto {
  @IsString()
  @IsNotEmpty()
  jobId: string;
}

export class MqttJobMessageDto {
  @IsString()
  @IsNotEmpty()
  @MaxLength(64)
  ticket: string;

  @IsOptional()
  @IsString()
  @MaxLength(200)
  title?: string;

  @IsOptional()
  @IsString()
  @MaxLength(4000)
  description?: string;

  @IsOptional()
  @IsString()
  @MaxLength(400)
  address?: string;
}
