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

interface ApiTokenAttributes {
    id: string;
    userId: string;
    name: string;
    prefix: string;
    tokenHash: string;
    lastUsedAt?: Date | null;
    expiresAt?: Date | null;
    isActive: boolean;
    createdAt: Date;
    updatedAt: Date;
}

interface ApiTokenCreationAttributes extends Optional<ApiTokenAttributes, 'id' | 'lastUsedAt' | 'expiresAt' | 'isActive' | 'createdAt' | 'updatedAt'> { }

class ApiToken extends Model<ApiTokenAttributes, ApiTokenCreationAttributes> implements ApiTokenAttributes {
    public id!: string;
    public userId!: string;
    public name!: string;
    public prefix!: string;
    public tokenHash!: string;
    public lastUsedAt?: Date | null;
    public expiresAt?: Date | null;
    public isActive!: boolean;
    public createdAt!: Date;
    public updatedAt!: Date;
}

ApiToken.init(
    {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true,
        },
        userId: {
            type: DataTypes.UUID,
            allowNull: false,
            field: 'user_id',
            references: {
                model: 'users',
                key: 'user_id',
            },
        },
        name: {
            type: DataTypes.STRING(100),
            allowNull: false,
        },
        prefix: {
            type: DataTypes.STRING(10),
            allowNull: false,
        },
        tokenHash: {
            type: DataTypes.STRING,
            allowNull: false,
            field: 'token_hash',
        },
        lastUsedAt: {
            type: DataTypes.DATE,
            allowNull: true,
            field: 'last_used_at',
        },
        expiresAt: {
            type: DataTypes.DATE,
            allowNull: true,
            field: 'expires_at',
        },
        isActive: {
            type: DataTypes.BOOLEAN,
            defaultValue: true,
            field: 'is_active',
            allowNull: false,
        },
        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: 'ApiToken',
        tableName: 'api_tokens',
        timestamps: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
    }
);

// Define associations
ApiToken.belongsTo(User, { foreignKey: 'userId', as: 'user' });
User.hasMany(ApiToken, { foreignKey: 'userId', as: 'apiTokens' });

export { ApiToken };
