import {
  DataTypes,
  Model,
  type CreationOptional,
  type InferAttributes,
  type InferCreationAttributes,
  type Sequelize,
} from 'sequelize';
import type { Db } from '@/db/types';
import type {
  BelongsToGetAssociationMixin,
  BelongsToSetAssociationMixin,
} from 'sequelize';
import type { Users } from './users';

export class File extends Model<
  InferAttributes<File>,
  InferCreationAttributes<File>
> {
  declare id: CreationOptional<string>;
  declare belongsTo: string | null;
  declare belongsToId: string | null;
  declare belongsToColumn: string | null;
  declare name: string;
  declare sizeInBytes: number | null;
  declare privateUrl: string | null;
  declare publicUrl: string;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
  declare deletedAt: CreationOptional<Date | null>;
  declare createdById: CreationOptional<string | null>;
  declare updatedById: CreationOptional<string | null>;


  declare getCreatedBy: BelongsToGetAssociationMixin<Users>;
  declare setCreatedBy: BelongsToSetAssociationMixin<Users, string>;
  declare getUpdatedBy: BelongsToGetAssociationMixin<Users>;
  declare setUpdatedBy: BelongsToSetAssociationMixin<Users, string>;

  static associate(db: Db): void {
    db.file.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.file.belongsTo(db.users, {
      as: 'updatedBy',
    });
  }
}

export default function (sequelize: Sequelize): typeof File {
  File.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      belongsTo: DataTypes.STRING(255),
      belongsToId: DataTypes.UUID,
      belongsToColumn: DataTypes.STRING(255),
      name: {
        type: DataTypes.STRING(2083),
        allowNull: false,
        validate: {
          notEmpty: true,
        },
      },
      sizeInBytes: {
        type: DataTypes.INTEGER,
        allowNull: true,
      },
      privateUrl: {
        type: DataTypes.STRING(2083),
        allowNull: true,
      },
      publicUrl: {
        type: DataTypes.STRING(2083),
        allowNull: false,
        validate: {
          notEmpty: true,
        },
      },
      createdAt: { type: DataTypes.DATE },
      updatedAt: { type: DataTypes.DATE },
      deletedAt: { type: DataTypes.DATE },
      createdById: { type: DataTypes.UUID, allowNull: true },
      updatedById: { type: DataTypes.UUID, allowNull: true },
    },
    {
      sequelize,
      modelName: 'file',
      timestamps: true,
      paranoid: true,
    },
  );

  return File;
}
