const mongoose = require('mongoose');
const { tenantFields, applyPlatformPlugins } = require('../platformFields');

const schema = new mongoose.Schema({
  ...tenantFields,
  run: { type: mongoose.Schema.ObjectId, ref: 'AgentRun', required: true, index: true },
  sequence: { type: Number, required: true },
  stepId: { type: String, index: true },
  attempt: { type: Number, default: 1 },
  kind: { type: String, enum: ['model', 'tool', 'approval', 'output'], required: true },
  tool: String,
  input: mongoose.Schema.Types.Mixed,
  plannedInput: mongoose.Schema.Types.Mixed,
  output: mongoose.Schema.Types.Mixed,
  outputSummary: String,
  citations: [{ title: String, url: String, sourceId: mongoose.Schema.ObjectId, location: String }],
  requiresApproval: { type: Boolean, default: false },
  approvalId: { type: mongoose.Schema.ObjectId, ref: 'AgentApproval' },
  provider: String,
  usage: { inputTokens: { type: Number, default: 0 }, outputTokens: { type: Number, default: 0 }, totalTokens: { type: Number, default: 0 } },
  cost: { amount: { type: Number, default: 0 }, currency: { type: String, default: 'NGN' } },
  status: { type: String, enum: ['queued', 'running', 'needs_approval', 'succeeded', 'failed', 'skipped'], default: 'queued' },
  durationMs: Number,
  retryCount: { type: Number, default: 0 },
  error: String,
  startedAt: Date,
  completedAt: Date,
});

module.exports = mongoose.model('AgentRunStep', applyPlatformPlugins(schema));
