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

export class EmbedConfigRepository {
  private repo: Repository<EmbedConfig>;

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

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

  findByEmbedKey(embedKey: string): Promise<EmbedConfig | null> {
    return this.repo.findOne({
      where: { embedKey, isActive: true },
      relations: ['eventType', 'eventType.user', 'user'],
    });
  }

  findById(id: string): Promise<EmbedConfig | null> {
    return this.repo.findOne({ where: { id }, relations: ['eventType'] });
  }

  findByEventTypeId(userId: string, eventTypeId: string): Promise<EmbedConfig | null> {
    return this.repo.findOne({
      where: { userId, eventTypeId, isActive: true },
      relations: ['eventType'],
    });
  }

  findAllActive(): Promise<EmbedConfig[]> {
    return this.repo.find({ where: { isActive: true } });
  }

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

  async update(id: string, data: Partial<EmbedConfig>): Promise<EmbedConfig> {
    await this.repo.update(id, data);
    const config = await this.findById(id);
    if (!config) throw new Error('Embed config not found');
    return config;
  }

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