import { Injectable } from '@nestjs/common';
import { CrmTimelineType } from '@prisma/client';
import { PrismaService } from '../../../prisma/prisma.service';
import { PaginatedResult } from '../core/entity-manager.base';

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

  async getByDeal(dealId: string, cursor?: string, limit = 30): Promise<PaginatedResult<any>> {
    const take = Math.min(limit, 100);
    const items = await this.prisma.crmTimeline.findMany({
      where: { dealId },
      take: take + 1,
      ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
      orderBy: { createdAt: 'desc' },
      include: {
        user: { select: { id: true, firstName: true, lastName: true } },
      },
    });

    const hasMore = items.length > take;
    const data = hasMore ? items.slice(0, -1) : items;
    return {
      data,
      nextCursor: hasMore ? data[data.length - 1].id : null,
      hasMore,
    };
  }

  async addEntry(
    dealId: string,
    userId: string | null,
    type: CrmTimelineType,
    data: {
      subject?: string;
      content?: string;
      metadata?: any;
    },
  ): Promise<any> {
    return this.prisma.crmTimeline.create({
      data: {
        dealId,
        userId,
        type,
        subject: data.subject,
        content: data.content,
        metadata: data.metadata,
      },
      include: {
        user: { select: { id: true, firstName: true, lastName: true } },
      },
    });
  }

  async pin(id: string): Promise<any> {
    return this.prisma.crmTimeline.update({
      where: { id },
      data: { pinnedAt: new Date() },
    });
  }

  async unpin(id: string): Promise<any> {
    return this.prisma.crmTimeline.update({
      where: { id },
      data: { pinnedAt: null },
    });
  }
}
