import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { TenantAwareRepository } from '../../../common/repositories/tenant-aware.repository';
import { ActivityEntity } from '../../../entities/activity.entity';

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

  async findAllWithDestination(): Promise<ActivityEntity[]> {
    const tenantId = this.getTenantId();
    return this.repo.find({
      where: { tenant_id: tenantId, is_deleted: false },
      relations: {
        destination: true,
        tickets: true,
      },
      order: { name: 'ASC' },
    });
  }

  async findByIdWithRelations(id: string): Promise<ActivityEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: { id, tenant_id: tenantId, is_deleted: false },
      relations: {
        destination: true,
        tickets: { slots: true },
      },
      // Activity edit form re-uses sort_order on slots to keep the
      // round-trip stable (display = same order the user saved).
      order: { tickets: { slots: { sort_order: 'ASC' } } } as any,
    });
  }

  async findByNameAndDestination(
    name: string,
    destinationId: string,
  ): Promise<ActivityEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: { name, destination_id: destinationId, tenant_id: tenantId, is_deleted: false },
    });
  }

  async findByShortCode(code: string): Promise<ActivityEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: { short_code: code, tenant_id: tenantId, is_deleted: false },
    });
  }
}
