import mongoose, { Schema, Document } from 'mongoose';
import { ApiKey as ApiKeyType } from '../types';

export interface ApiKeyDocument extends Omit<ApiKeyType, 'id'>, Document {
  id: number;
}

const apiKeySchema = new Schema<ApiKeyDocument>(
  {
    id: { type: Number, required: true, unique: true },
    name: { type: String, required: true },
    keyHash: { type: String, required: true, unique: true },
    keyPrefix: { type: String, required: true },
    isActive: { type: Boolean, default: true },
    expiresAt: { type: Date, default: null },
    lastUsedAt: { type: Date, default: null },
  },
  {
    timestamps: true,
    toJSON: {
      transform: (_doc, ret: Record<string, unknown>) => {
        delete ret._id;
        delete ret.__v;
        delete ret.keyHash; // Never expose the hash
        return ret;
      },
    },
  }
);

// Indexes
apiKeySchema.index({ keyHash: 1 });
apiKeySchema.index({ keyPrefix: 1 });
apiKeySchema.index({ isActive: 1, expiresAt: 1 });

export const ApiKey = mongoose.model<ApiKeyDocument>('ApiKey', apiKeySchema);
