import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { FindOptionsOrder, Repository } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { TenantAwareRepository } from '../../../common/repositories/tenant-aware.repository';
import { ActivityTicketJourneyEntity } from '../../../entities/activity-ticket-journey.entity';
import { CLS_USER_ID } from '../../../common/cls/cls.constants';

@Injectable()
export class ActivityTicketJourneyRepository extends TenantAwareRepository<ActivityTicketJourneyEntity> {
  constructor(
    @InjectRepository(ActivityTicketJourneyEntity) repo: Repository<ActivityTicketJourneyEntity>,
    cls: ClsService,
  ) {
    super(repo, cls);
  }

  async logEvent(data: {
    ticket_item_id: string;
    event: string;
    booking_id?: string | null;
    booking_activity_item_id?: string | null;
    from_path?: string | null;
    to_path?: string | null;
    notes?: string | null;
  }): Promise<void> {
    const userId = this.cls.get<string>(CLS_USER_ID) ?? null;
    await this.save({
      ...data,
      booking_id: data.booking_id ?? null,
      booking_activity_item_id: data.booking_activity_item_id ?? null,
      from_path: data.from_path ?? null,
      to_path: data.to_path ?? null,
      notes: data.notes ?? null,
      created_by: userId,
      updated_by: userId,
    });
  }

  async findByTicketItem(ticketItemId: string): Promise<ActivityTicketJourneyEntity[]> {
    const tenantId = this.getTenantId();
    return this.repo.find({
      where: { tenant_id: tenantId, ticket_item_id: ticketItemId, is_deleted: false },
      order: { created_at: 'ASC' } as FindOptionsOrder<ActivityTicketJourneyEntity>,
    });
  }
}
