/**
 * WorkflowTemplate Model
 *
 * Manages guided workflow templates that Super Admin creates and users see on
 * their dashboard. Steps and actions are embedded sub-documents because they are
 * always loaded together with the template.
 *
 * Soft-delete pattern: deletedAt field marks deletion without losing user progress.
 * Version field: incremented on edits for future versioning support.
 */

import mongoose, { Schema, Document, Types } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type WorkflowTemplateStatus = 'draft' | 'active' | 'inactive' | 'archived';
export type CompletionRule = 'single_action' | 'any_of_actions' | 'all_of_actions';

export interface IWorkflowStepAction extends Document {
  actionKey: string;
  label: string;
  module: string;
  route: string;
  completionEvent: string;
  completionKey: string;
  actionOrder: number;
}

export interface IWorkflowStep extends Document {
  stepKey: string;
  title: string;
  description: string;
  stepOrder: number;
  icon: string;
  ctaLabel: string;
  route: string;
  completionRule: CompletionRule;
  completionTrigger?: string;
  helpText?: string;
  estimatedDuration?: string;
  actions: IWorkflowStepAction[];
}

export interface IWorkflowTemplate extends Document {
  name: string;
  slug: string;
  description: string;
  status: WorkflowTemplateStatus;
  displayOrder: number;
  icon: string;
  category?: string;
  targetAudience?: string;
  startDate?: Date;
  endDate?: Date;
  version: number;
  createdById?: string;
  steps: IWorkflowStep[];
  deletedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// ACTION SUB-SCHEMA
// ============================================

const WorkflowStepActionSchema = new Schema<IWorkflowStepAction>(
  {
    actionKey: { type: String, required: true, trim: true },
    label: { type: String, required: true, trim: true },
    module: { type: String, required: true, trim: true },
    route: { type: String, required: true, trim: true },
    completionEvent: { type: String, required: true, trim: true },
    completionKey: { type: String, required: true, trim: true },
    actionOrder: { type: Number, required: true, default: 0 },
  },
  { _id: true, timestamps: false }
);

// ============================================
// STEP SUB-SCHEMA
// ============================================

const WorkflowStepSchema = new Schema<IWorkflowStep>(
  {
    stepKey: { type: String, required: true, trim: true },
    title: { type: String, required: true, trim: true },
    description: { type: String, required: true, trim: true },
    stepOrder: { type: Number, required: true, default: 0 },
    icon: { type: String, required: true, trim: true, default: 'Circle' },
    ctaLabel: { type: String, required: true, trim: true, default: 'Start' },
    route: { type: String, required: true, trim: true },
    completionRule: {
      type: String,
      enum: ['single_action', 'any_of_actions', 'all_of_actions'],
      required: true,
      default: 'single_action',
    },
    completionTrigger: { type: String, trim: true },
    helpText: { type: String, trim: true },
    estimatedDuration: { type: String, trim: true },
    actions: [WorkflowStepActionSchema],
  },
  { _id: true, timestamps: false }
);

// ============================================
// TEMPLATE SCHEMA
// ============================================

const WorkflowTemplateSchema = new Schema<IWorkflowTemplate>(
  {
    name: { type: String, required: true, trim: true },
    slug: { type: String, required: true, trim: true, unique: true },
    description: { type: String, required: true, trim: true },
    status: {
      type: String,
      enum: ['draft', 'active', 'inactive', 'archived'],
      required: true,
      default: 'draft',
      index: true,
    },
    displayOrder: { type: Number, default: 0 },
    icon: { type: String, trim: true, default: 'Rocket' },
    category: { type: String, trim: true },
    targetAudience: { type: String, trim: true },
    startDate: { type: Date },
    endDate: { type: Date },
    version: { type: Number, default: 1 },
    createdById: { type: String },
    steps: [WorkflowStepSchema],
    deletedAt: { type: Date },
  },
  {
    timestamps: true,
    collection: 'workflowtemplates',
  }
);

// Performance indexes
WorkflowTemplateSchema.index({ status: 1, displayOrder: 1 });
WorkflowTemplateSchema.index({ slug: 1 }, { unique: true });

// Filter out soft-deleted docs by default
WorkflowTemplateSchema.pre(/^find/, function (this: any, next: any) {
  if (this.getFilter().deletedAt !== undefined) return next();
  // Don't filter on individual .findById() calls — only on list queries
  if (this.getFilter()._id) return next();
  this.where({ deletedAt: null });
  next();
});

export const WorkflowTemplate =
  mongoose.models.WorkflowTemplate ||
  mongoose.model<IWorkflowTemplate>('WorkflowTemplate', WorkflowTemplateSchema);