import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../infrastructure/database/prisma.service';
import { LibraryService } from '../library/library.service';
import { SyncBootstrapResponseDto, SyncChangesResponseDto } from './sync.dto';

@Injectable()
export class SyncService {
  constructor(
    private readonly prismaService: PrismaService,
    private readonly libraryService: LibraryService,
  ) {}

  async bootstrap(): Promise<SyncBootstrapResponseDto> {
    const latestCursor = await this.getLatestCursor();

    return {
      nextCursor: latestCursor,
      tracks: await this.libraryService.getBootstrapTracks(),
      events: [],
      deletedTrackIds: [],
      serverTime: new Date().toISOString(),
    };
  }

  async changes(after: string): Promise<SyncChangesResponseDto> {
    const latestCursor = await this.getLatestCursor();
    const normalizedCursor =
      BigInt(latestCursor) > BigInt(after) ? latestCursor : after;

    return {
      nextCursor: normalizedCursor,
      tracks: [],
      events: [],
      deletedTrackIds: [],
      serverTime: new Date().toISOString(),
    };
  }

  private async getLatestCursor(): Promise<string> {
    const latest = await this.prismaService.libraryEvent.findFirst({
      orderBy: {
        id: 'desc',
      },
    });

    return latest?.id.toString() ?? '0';
  }
}
