import mongoose from 'mongoose';
import { generateId } from '../../utils.js';

// Define the device schema
const deviceInfoSchema = new mongoose.Schema(
  {
    os: {
      platform: { type: String },
      type: { type: String },
      release: { type: String },
      arch: { type: String },
      hostname: { type: String },
      uptime: { type: Number },
    },
    cpu: {
      cores: { type: Number },
      model: { type: String },
      speedMHz: { type: Number },
    },
    memory: {
      totalGB: { type: String }, // stored as string from .toFixed(2), could also use Number
      freeGB: { type: String },
    },
    network: {
      type: mongoose.Schema.Types.Mixed, // since it's an object with dynamic interface names
    },
    user: {
      uid: { type: Number },
      gid: { type: Number },
      username: { type: String },
      homedir: { type: String },
      shell: { type: String },
    },
    process: {
      nodeVersion: { type: String },
      pid: { type: Number },
      cwd: { type: String },
      execPath: { type: String },
    },
  },
  { _id: false }
);

const hostSchema = new mongoose.Schema(
  {
    _reference: { type: String, default: () => generateId()() },
    name: { required: true, type: String },
    tags: [{ required: false, type: String }],
    online: { required: true, type: Boolean, default: false },
    state: {
      type: { type: String, required: true, default: 'offline' },
      message: { type: String, required: false },
      percent: { type: Number, required: false },
    },
    active: { required: true, type: Boolean, default: true },
    connectedAt: { required: false, type: Date },
    authCode: { type: { required: false, type: String } },
    deviceInfo: { deviceInfoSchema },
    files: [{ type: mongoose.Schema.Types.ObjectId, ref: 'file' }],
  },
  { timestamps: true }
);

hostSchema.virtual('id').get(function () {
  return this._id;
});

hostSchema.set('toJSON', { virtuals: true });

export const hostModel = mongoose.model('host', hostSchema);
