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

export interface ISyncSessionDocument extends Document {
  user: Types.ObjectId;
  local_id: number;
  login_time: Date;
  logout_time?: Date | null;
  total_work_seconds: number;
  total_break_seconds: number;
  total_idle_seconds: number;
  status?: string;
  device_name?: string;
  operating_system?: string;
  ip_address?: string;
  createdAt: Date;
  updatedAt: Date;
}

const syncSessionSchema = new Schema<ISyncSessionDocument>(
  {
    user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    local_id: { type: Number, required: true },
    login_time: { type: Date, required: true },
    logout_time: { type: Date, default: null },
    total_work_seconds: { type: Number, default: 0 },
    total_break_seconds: { type: Number, default: 0 },
    total_idle_seconds: { type: Number, default: 0 },
    status: { type: String },
    device_name: { type: String },
    operating_system: { type: String },
    ip_address: { type: String },
  },
  { timestamps: true },
);

// local_id is a per-device SQLite autoincrement counter, not globally unique
// per employee (a reinstall or second device restarts it at 1) — device_name
// disambiguates so a new device's session doesn't silently overwrite an
// unrelated older one that happens to share the same local_id.
syncSessionSchema.index({ user: 1, device_name: 1, local_id: 1 }, { unique: true });

export default mongoose.model<ISyncSessionDocument>('SyncSession', syncSessionSchema);
