import mongoose, { Document, Schema, Types } from 'mongoose';

export const LOG_TYPES = ['BREAK_START', 'BREAK_END', 'IDLE', 'ACTIVE', 'CHECKOUT', 'CHECKIN', 'BREAK'] as const;
export type LogType = (typeof LOG_TYPES)[number];

// Selectable break categories for the typed-break API. Hardcoded on purpose.
export const BREAK_TYPES = ['Training', 'Meeting', 'Lunch', 'Tea', 'Personal', 'Other'] as const;
export type BreakType = (typeof BREAK_TYPES)[number];

// System-detected reasons a break gets logged automatically (not user-selectable,
// so not part of BREAK_TYPES / GET /break-types). Unlike a normal typed break,
// this one is deducted from working time since there was no live tracking to
// otherwise account for the gap.
export const SYSTEM_BREAK_TYPES = ['TRACKING_INTERRUPTED'] as const;
export type SystemBreakType = (typeof SYSTEM_BREAK_TYPES)[number];

export const ALL_BREAK_TYPES = [...BREAK_TYPES, ...SYSTEM_BREAK_TYPES] as const;
export type AnyBreakType = BreakType | SystemBreakType;

export interface IOsInfo {
  os?: string;
  network?: string;
}

export interface IDesktopSessionDocument extends Document {
  user: Types.ObjectId;
  log_type: LogType;
  timestamp: Date;
  createdAt: Date;
  ip_address?: string;
  os_info?: IOsInfo;
  device_name?: string;
  break_type?: AnyBreakType;
  end_time?: Date;
  duration_seconds?: number;
  is_auto_checkout?: boolean;
}

const desktopSessionSchema = new Schema<IDesktopSessionDocument>({
  user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  log_type: { type: String, enum: LOG_TYPES, required: true },
  timestamp: { type: Date, required: true, default: Date.now },
  createdAt: { type: Date, default: Date.now },
  ip_address: { type: String },
  os_info: {
    os: { type: String },
    network: { type: String },
  },
  device_name: { type: String },
  break_type: { type: String, enum: ALL_BREAK_TYPES },
  end_time: { type: Date },
  duration_seconds: { type: Number, min: 0 },
  // True only for a CHECKOUT the auto-checkout cron inserted on the
  // employee's behalf (session left open past midnight); absent/false for a
  // manual checkout.
  is_auto_checkout: { type: Boolean, default: false },
});

desktopSessionSchema.index({ user: 1, timestamp: -1 });
desktopSessionSchema.index({ timestamp: 1 });

export default mongoose.model<IDesktopSessionDocument>('DesktopSession', desktopSessionSchema);
