import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';

export type TrackingCoverageSnapshotDocument =
  HydratedDocument<TrackingCoverageSnapshot>;

@Schema({ _id: false })
export class TrackingCoverageGap {
  @Prop({ required: true })
  from: Date;

  @Prop({ required: true })
  to: Date;

  @Prop({ required: true })
  durationMinutes: number;

  @Prop({ required: true })
  reason: string;

  @Prop()
  suspectedCause?: string;
}

@Schema({ _id: false })
export class TrackingCoverageLegSnapshot {
  @Prop({ required: true })
  legId: string;

  @Prop({ required: true })
  legNumber: number;

  @Prop()
  fromLocation?: string;

  @Prop()
  toLocation?: string;

  @Prop()
  departureAt?: Date;

  @Prop()
  arrivalAt?: Date;

  @Prop({ required: true })
  expectedDurationMinutes: number;

  @Prop({ required: true })
  trackedDurationMinutes: number;

  @Prop({ required: true })
  gapDurationMinutes: number;

  @Prop({ required: true })
  coveragePercent: number;

  @Prop({ required: true })
  pointCount: number;

  @Prop({ type: [TrackingCoverageGap], default: [] })
  gaps: TrackingCoverageGap[];
}

@Schema({ collection: 'tracking_coverage_snapshots', timestamps: true })
export class TrackingCoverageSnapshot {
  @Prop({ required: true, unique: true, index: true })
  requestId: string;

  @Prop({ required: true, index: true })
  tripDbId: string;

  @Prop({ type: [TrackingCoverageLegSnapshot], default: [] })
  legs: TrackingCoverageLegSnapshot[];

  @Prop({ type: Object, required: true })
  summary: {
    expectedDurationMinutes: number;
    trackedDurationMinutes: number;
    gapDurationMinutes: number;
    coveragePercent: number;
  };

  @Prop({ required: true })
  computedAt: Date;
}

export const TrackingCoverageGapSchema =
  SchemaFactory.createForClass(TrackingCoverageGap);
export const TrackingCoverageLegSnapshotSchema = SchemaFactory.createForClass(
  TrackingCoverageLegSnapshot,
);
export const TrackingCoverageSnapshotSchema = SchemaFactory.createForClass(
  TrackingCoverageSnapshot,
);
