import { DataTypes, Model, Optional } from 'sequelize';
import { sequelize } from '@config/database';
import { WorkflowRequest } from './WorkflowRequest';

interface DealerCompletionDetailsAttributes {
  completionId: string;
  requestId: string;
  activityCompletionDate: Date;
  numberOfParticipants?: number;
  totalClosedExpenses?: number;
  submittedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

interface DealerCompletionDetailsCreationAttributes extends Optional<DealerCompletionDetailsAttributes, 'completionId' | 'numberOfParticipants' | 'totalClosedExpenses' | 'submittedAt' | 'createdAt' | 'updatedAt'> {}

class DealerCompletionDetails extends Model<DealerCompletionDetailsAttributes, DealerCompletionDetailsCreationAttributes> implements DealerCompletionDetailsAttributes {
  public completionId!: string;
  public requestId!: string;
  public activityCompletionDate!: Date;
  public numberOfParticipants?: number;
  public totalClosedExpenses?: number;
  public submittedAt?: Date;
  public createdAt!: Date;
  public updatedAt!: Date;

  public workflowRequest?: WorkflowRequest;
}

DealerCompletionDetails.init(
  {
    completionId: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      field: 'completion_id'
    },
    requestId: {
      type: DataTypes.UUID,
      allowNull: false,
      unique: true,
      field: 'request_id',
      references: {
        model: 'workflow_requests',
        key: 'request_id'
      }
    },
    activityCompletionDate: {
      type: DataTypes.DATEONLY,
      allowNull: false,
      field: 'activity_completion_date'
    },
    numberOfParticipants: {
      type: DataTypes.INTEGER,
      allowNull: true,
      field: 'number_of_participants'
    },
    totalClosedExpenses: {
      type: DataTypes.DECIMAL(15, 2),
      allowNull: true,
      field: 'total_closed_expenses'
    },
    submittedAt: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'submitted_at'
    },
    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: 'DealerCompletionDetails',
    tableName: 'dealer_completion_details',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      {
        unique: true,
        fields: ['request_id']
      }
    ]
  }
);

DealerCompletionDetails.belongsTo(WorkflowRequest, {
  as: 'workflowRequest',
  foreignKey: 'requestId',
  targetKey: 'requestId'
});

WorkflowRequest.hasOne(DealerCompletionDetails, {
  as: 'completionDetails',
  foreignKey: 'requestId',
  sourceKey: 'requestId'
});

export { DealerCompletionDetails };

