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

export interface Form1626asUploadLogAttributes {
  id: number;
  uploadedAt: Date;
  uploadedBy: string;
  fileName?: string | null;
  recordsImported: number;
  errorsCount: number;
}

interface Form1626asUploadLogCreationAttributes
  extends Optional<Form1626asUploadLogAttributes, 'id' | 'fileName'> {}

class Form1626asUploadLog
  extends Model<Form1626asUploadLogAttributes, Form1626asUploadLogCreationAttributes>
  implements Form1626asUploadLogAttributes
{
  public id!: number;
  public uploadedAt!: Date;
  public uploadedBy!: string;
  public fileName?: string | null;
  public recordsImported!: number;
  public errorsCount!: number;

  public uploadedByUser?: User;
}

Form1626asUploadLog.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    uploadedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      field: 'uploaded_at',
    },
    uploadedBy: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'uploaded_by',
      references: { model: 'users', key: 'user_id' },
    },
    fileName: {
      type: DataTypes.STRING(255),
      allowNull: true,
      field: 'file_name',
    },
    recordsImported: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      field: 'records_imported',
    },
    errorsCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      field: 'errors_count',
    },
  },
  {
    sequelize,
    tableName: 'form_16_26as_upload_log',
    timestamps: false,
    underscored: true,
  }
);

Form1626asUploadLog.belongsTo(User, {
  as: 'uploadedByUser',
  foreignKey: 'uploadedBy',
  targetKey: 'userId',
});

export { Form1626asUploadLog };
