import { DataTypes, Model, Optional } from 'sequelize';
import { sequelize } from '@config/database';
import { User } from './User';
import { Priority, WorkflowStatus } from '../types/common.types';

interface WorkflowRequestAttributes {
  requestId: string;
  requestNumber: string;
  initiatorId: string;
  templateType: 'CUSTOM' | 'TEMPLATE' | 'DEALER CLAIM' | 'FORM_16';
  workflowType?: string;  // 'NON_TEMPLATIZED' | 'CLAIM_MANAGEMENT' | etc.
  templateId?: string;    // Reference to workflow_templates if using admin template
  title: string;
  description: string;
  priority: Priority;
  status: WorkflowStatus;
  currentLevel: number;
  totalLevels: number;
  totalTatHours: number;
  submissionDate?: Date;
  closureDate?: Date;
  conclusionRemark?: string;
  aiGeneratedConclusion?: string;
  isDraft: boolean;
  isDeleted: boolean;
  isPaused: boolean;
  pausedAt?: Date;
  pausedBy?: string;
  pauseReason?: string;
  pauseResumeDate?: Date;
  pauseTatSnapshot?: any;
  createdAt: Date;
  updatedAt: Date;
}

interface WorkflowRequestCreationAttributes extends Optional<WorkflowRequestAttributes, 'requestId' | 'submissionDate' | 'closureDate' | 'conclusionRemark' | 'aiGeneratedConclusion' | 'isPaused' | 'pausedAt' | 'pausedBy' | 'pauseReason' | 'pauseResumeDate' | 'pauseTatSnapshot' | 'createdAt' | 'updatedAt'> { }

class WorkflowRequest extends Model<WorkflowRequestAttributes, WorkflowRequestCreationAttributes> implements WorkflowRequestAttributes {
  public requestId!: string;
  public requestNumber!: string;
  public initiatorId!: string;
  public templateType!: 'CUSTOM' | 'TEMPLATE' | 'DEALER CLAIM' | 'FORM_16';
  public workflowType?: string;
  public templateId?: string;
  public title!: string;
  public description!: string;
  public priority!: Priority;
  public status!: WorkflowStatus;
  public currentLevel!: number;
  public totalLevels!: number;
  public totalTatHours!: number;
  public submissionDate?: Date;
  public closureDate?: Date;
  public conclusionRemark?: string;
  public aiGeneratedConclusion?: string;
  public isDraft!: boolean;
  public isDeleted!: boolean;
  public isPaused!: boolean;
  public pausedAt?: Date;
  public pausedBy?: string;
  public pauseReason?: string;
  public pauseResumeDate?: Date;
  public pauseTatSnapshot?: any;
  public createdAt!: Date;
  public updatedAt!: Date;

  // Associations
  public initiator?: User;
}

WorkflowRequest.init(
  {
    requestId: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      field: 'request_id'
    },
    requestNumber: {
      type: DataTypes.STRING(20),
      allowNull: false,
      unique: true,
      field: 'request_number'
    },
    initiatorId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'initiator_id',
      references: {
        model: 'users',
        key: 'user_id'
      }
    },
    templateType: {
      type: DataTypes.STRING(20),
      defaultValue: 'CUSTOM',
      field: 'template_type'
    },
    workflowType: {
      type: DataTypes.STRING(50),
      allowNull: true,
      defaultValue: 'NON_TEMPLATIZED',
      field: 'workflow_type',
      // Don't fail if column doesn't exist (for backward compatibility with old environments)
      // Sequelize will handle this gracefully if the column is missing
    },
    templateId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'template_id',
      references: {
        model: 'workflow_templates',
        key: 'template_id'
      }
    },
    title: {
      type: DataTypes.STRING(500),
      allowNull: false
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: false
    },
    priority: {
      type: DataTypes.ENUM('STANDARD', 'EXPRESS'),
      defaultValue: 'STANDARD'
    },
    status: {
      type: DataTypes.ENUM('DRAFT', 'PENDING', 'IN_PROGRESS', 'APPROVED', 'REJECTED', 'CLOSED'),
      defaultValue: 'DRAFT'
    },
    currentLevel: {
      type: DataTypes.INTEGER,
      defaultValue: 1,
      field: 'current_level'
    },
    totalLevels: {
      type: DataTypes.INTEGER,
      defaultValue: 1,
      field: 'total_levels',
      validate: {
        max: 10
      }
    },
    totalTatHours: {
      type: DataTypes.DECIMAL(10, 2),
      defaultValue: 0,
      field: 'total_tat_hours'
    },
    submissionDate: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'submission_date'
    },
    closureDate: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'closure_date'
    },
    conclusionRemark: {
      type: DataTypes.TEXT,
      allowNull: true,
      field: 'conclusion_remark'
    },
    aiGeneratedConclusion: {
      type: DataTypes.TEXT,
      allowNull: true,
      field: 'ai_generated_conclusion'
    },
    isDraft: {
      type: DataTypes.BOOLEAN,
      defaultValue: true,
      field: 'is_draft'
    },
    isDeleted: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
      field: 'is_deleted'
    },
    isPaused: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
      field: 'is_paused'
    },
    pausedAt: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'paused_at'
    },
    pausedBy: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'paused_by',
      references: {
        model: 'users',
        key: 'user_id'
      }
    },
    pauseReason: {
      type: DataTypes.TEXT,
      allowNull: true,
      field: 'pause_reason'
    },
    pauseResumeDate: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'pause_resume_date'
    },
    pauseTatSnapshot: {
      type: DataTypes.JSONB,
      allowNull: true,
      field: 'pause_tat_snapshot'
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      field: 'created_at'
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      field: 'updated_at'
    }
  },
  {
    sequelize,
    modelName: 'WorkflowRequest',
    tableName: 'workflow_requests',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      {
        fields: ['initiator_id']
      },
      {
        fields: ['status']
      },
      {
        unique: true,
        fields: ['request_number']
      },
      {
        fields: ['created_at']
      },
      {
        fields: ['workflow_type']
      },
      {
        fields: ['template_id']
      }
    ]
  }
);

// Associations
WorkflowRequest.belongsTo(User, {
  as: 'initiator',
  foreignKey: 'initiatorId',
  targetKey: 'userId'
});

export { WorkflowRequest };
