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 { Organizations } from './organizations';
import type { Users } from './users';

export class AuthRefreshTokens extends Model<
  InferAttributes<AuthRefreshTokens>,
  InferCreationAttributes<AuthRefreshTokens>
> {
  declare id: CreationOptional<string>;
  declare userId: string;
  declare organizationId: string | null;
  declare tokenHash: string;
  declare familyId: string;
  declare previousTokenId: string | null;
  declare userAgent: string | null;
  declare ipAddress: string | null;
  declare expiresAt: Date;
  declare revokedAt: Date | null;
  declare replacedByTokenId: string | null;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;


  declare getUser: BelongsToGetAssociationMixin<Users>;
  declare setUser: BelongsToSetAssociationMixin<Users, string>;
  declare getOrganization: BelongsToGetAssociationMixin<Organizations>;
  declare setOrganization: BelongsToSetAssociationMixin<Organizations, string>;

  static associate(db: Db): void {
    db.auth_refresh_tokens.belongsTo(db.users, {
      as: 'user',
      foreignKey: {
        name: 'userId',
      },
      constraints: false,
    });

    db.auth_refresh_tokens.belongsTo(db.organizations, {
      as: 'organization',
      foreignKey: {
        name: 'organizationId',
      },
      constraints: false,
    });
  }
}

export default function (sequelize: Sequelize): typeof AuthRefreshTokens {
  AuthRefreshTokens.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      userId: {
        type: DataTypes.UUID,
        allowNull: false,
      },
      organizationId: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      tokenHash: {
        type: DataTypes.TEXT,
        allowNull: false,
        unique: true,
      },
      familyId: {
        type: DataTypes.UUID,
        allowNull: false,
      },
      previousTokenId: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      userAgent: {
        type: DataTypes.TEXT,
        allowNull: true,
      },
      ipAddress: {
        type: DataTypes.TEXT,
        allowNull: true,
      },
      expiresAt: {
        type: DataTypes.DATE,
        allowNull: false,
      },
      revokedAt: {
        type: DataTypes.DATE,
        allowNull: true,
      },
      replacedByTokenId: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      createdAt: { type: DataTypes.DATE },
      updatedAt: { type: DataTypes.DATE },
    },
    {
      sequelize,
      modelName: 'auth_refresh_tokens',
      timestamps: true,
      freezeTableName: true,
    },
  );

  return AuthRefreshTokens;
}
