import { Repository } from 'typeorm';
import { AppDataSource } from '../index';
import { BusyBlock } from '../entities/BusyBlock.entity';
import { generateUuid } from '../../utils/uuid';

export class BusyBlockRepository {
  private repo: Repository<BusyBlock>;

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

  async replaceForConnection(
    userId: string,
    connectionId: string,
    source: 'google' | 'microsoft' | 'apple',
    blocks: Array<{ start: Date; end: Date }>,
  ): Promise<void> {
    await this.repo.delete({ userId, sourceRef: connectionId });

    if (blocks.length === 0) return;

    const fetchedAt = new Date();
    const rows = blocks.map((b) =>
      this.repo.create({
        id: generateUuid(),
        userId,
        startTime: b.start,
        endTime: b.end,
        source,
        sourceRef: connectionId,
        fetchedAt,
      }),
    );
    await this.repo.save(rows);
  }

  async findInRange(
    userId: string,
    from: Date,
    to: Date,
  ): Promise<Array<{ start: Date; end: Date }>> {
    const rows = await this.repo
      .createQueryBuilder('b')
      .where('b.user_id = :userId', { userId })
      .andWhere('b.start_time < :to', { to })
      .andWhere('b.end_time > :from', { from })
      .getMany();

    return rows.map((r) => ({ start: r.startTime, end: r.endTime }));
  }

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