import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { randomBytes } from 'crypto';
import { ApiKey } from '../../entities/api-key.entity';

@Injectable()
export class ApiKeysService {
  constructor(
    @InjectRepository(ApiKey)
    private readonly apiKeyRepo: Repository<ApiKey>,
  ) {}

  async create(userId: string, name: string): Promise<{ apiKey: ApiKey; rawKey: string }> {
    const rawKey = `dh_${randomBytes(32).toString('hex')}`;
    const keyPrefix = rawKey.slice(0, 10);

    const apiKey = this.apiKeyRepo.create({
      userId,
      key: rawKey,
      name: name || 'CI/CD Key',
      keyPrefix,
    });

    await this.apiKeyRepo.save(apiKey);
    return { apiKey, rawKey };
  }

  async listByUser(userId: string): Promise<ApiKey[]> {
    return this.apiKeyRepo.find({
      where: { userId },
      order: { createdAt: 'DESC' },
    });
  }

  async revoke(id: string, userId: string): Promise<boolean> {
    const apiKey = await this.apiKeyRepo.findOne({ where: { id, userId } });
    if (!apiKey) return false;
    apiKey.isActive = false;
    await this.apiKeyRepo.save(apiKey);
    return true;
  }

  async delete(id: string, userId: string): Promise<boolean> {
    const apiKey = await this.apiKeyRepo.findOne({ where: { id, userId } });
    if (!apiKey) return false;
    await this.apiKeyRepo.remove(apiKey);
    return true;
  }
}
