import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class BlocksService {
  constructor(private prisma: PrismaService) {}

  findAll() {
    return this.prisma.block.findMany({ orderBy: { createdAt: 'asc' } });
  }

  async findByPath(path: string) {
    const existing = await this.prisma.block.findUnique({ where: { path } });
    if (existing) return existing;
    return this.prisma.block.create({
      data: { path, name: path, version: 'v0.1', isInPreview: false },
    });
  }

  update(path: string, data: { version?: string; isInPreview?: boolean; changelog?: object[] }) {
    return this.prisma.block.update({ where: { path }, data });
  }

  createSnapshot(blockPath: string, data: { version: string; changelog: object[]; html: string; css: string }) {
    return this.prisma.blockSnapshot.upsert({
      where: { blockPath_version: { blockPath, version: data.version } },
      update: { html: data.html, css: data.css, changelog: data.changelog },
      create: { blockPath, ...data },
    });
  }

  listSnapshots(blockPath: string) {
    return this.prisma.blockSnapshot.findMany({
      where: { blockPath },
      select: { id: true, version: true, createdAt: true },
      orderBy: { createdAt: 'desc' },
    });
  }

  getSnapshot(id: string) {
    return this.prisma.blockSnapshot.findUniqueOrThrow({ where: { id } });
  }
}
