import { Type } from 'class-transformer';
import {
  IsInt,
  IsObject,
  IsOptional,
  IsString,
  IsUrl,
  Matches,
  Max,
  MaxLength,
  Min,
  ValidateNested,
} from 'class-validator';

const BASE64_URL = /^[A-Za-z0-9_-]+={0,2}$/;

class PushSubscriptionKeysDto {
  @IsString()
  @MaxLength(512)
  @Matches(BASE64_URL)
  p256dh!: string;

  @IsString()
  @MaxLength(128)
  @Matches(BASE64_URL)
  auth!: string;
}

/** The browser-created subscription. Private VAPID material never reaches it. */
export class SavePushSubscriptionDto {
  @IsUrl({ protocols: ['https'], require_protocol: true })
  @MaxLength(2048)
  endpoint!: string;

  @IsOptional()
  @IsInt()
  @Min(0)
  @Max(Number.MAX_SAFE_INTEGER)
  expirationTime?: number | null;

  @IsObject()
  @ValidateNested()
  @Type(() => PushSubscriptionKeysDto)
  keys!: PushSubscriptionKeysDto;
}

export class RemovePushSubscriptionDto {
  @IsUrl({ protocols: ['https'], require_protocol: true })
  @MaxLength(2048)
  endpoint!: string;
}
