import { Repository } from 'typeorm';
import { AppDataSource } from '../index';
import { ApiKey } from '../entities/ApiKey.entity';

export class ApiKeyRepository {
  private repo: Repository<ApiKey>;

  constructor() {
    this.repo = AppDataSource.getRepository(ApiKey);
  }

  findByUserId(userId: string): Promise<ApiKey[]> {
    return this.repo.find({
      where: { userId, isActive: true },
      order: { createdAt: 'DESC' },
    });
  }

  findByHash(keyHash: string): Promise<ApiKey | null> {
    return this.repo.findOne({ where: { keyHash, isActive: true } });
  }

  create(data: Partial<ApiKey>): Promise<ApiKey> {
    return this.repo.save(this.repo.create(data));
  }

  async revoke(id: string): Promise<void> {
    await this.repo.update(id, { isActive: false });
  }

  updateLastUsed(id: string): Promise<void> {
    return this.repo.update(id, { lastUsedAt: new Date() }).then(() => undefined);
  }
}
