import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ApiKey } from '@domain/entities/api-key.entity';
import { ApiKeyRepository } from '@domain/ports/out/api-key.repository';
import { ApiKeyOrmEntity } from '../entities/api-key.orm-entity';
import { ApiKeyOrmMapper } from '../mappers/api-key-orm.mapper';

@Injectable()
export class TypeOrmApiKeyRepository implements ApiKeyRepository {
  constructor(
    @InjectRepository(ApiKeyOrmEntity)
    private readonly repo: Repository<ApiKeyOrmEntity>
  ) {}

  async save(apiKey: ApiKey): Promise<ApiKey> {
    const orm = ApiKeyOrmMapper.toOrm(apiKey);
    const saved = await this.repo.save(orm);
    return ApiKeyOrmMapper.toDomain(saved);
  }

  async findById(id: string): Promise<ApiKey | null> {
    const orm = await this.repo.findOne({ where: { id } });
    return orm ? ApiKeyOrmMapper.toDomain(orm) : null;
  }

  async findByKeyHash(keyHash: string): Promise<ApiKey | null> {
    const orm = await this.repo.findOne({ where: { keyHash } });
    return orm ? ApiKeyOrmMapper.toDomain(orm) : null;
  }

  async findByOrganizationId(organizationId: string): Promise<ApiKey[]> {
    const orms = await this.repo.find({
      where: { organizationId },
      order: { createdAt: 'DESC' },
    });
    return ApiKeyOrmMapper.toDomainMany(orms);
  }

  async delete(id: string): Promise<void> {
    await this.repo.delete({ id });
  }
}
