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 {
  CommunicationTemplateEntity,
  CommunicationChannel,
  CommunicationContext,
} from '../../../entities/communication-template.entity';

/**
 * Tenant-scoped repo for communication_templates. Adds a lookup keyed
 * on (channel, context) so the Query / Booking / MD pages can fetch
 * only the templates that belong to their own surface.
 */
@Injectable()
export class CommunicationTemplateRepository extends TenantAwareRepository<CommunicationTemplateEntity> {
  constructor(
    @InjectRepository(CommunicationTemplateEntity)
    repo: Repository<CommunicationTemplateEntity>,
    cls: ClsService,
  ) {
    super(repo, cls);
  }

  /**
   * All active templates for a given channel + context, ordered so the
   * `is_default` row is first (so the FE picker preselects it without
   * a client-side sort).
   */
  async findByChannelAndContext(
    channel: CommunicationChannel,
    context: CommunicationContext,
  ): Promise<CommunicationTemplateEntity[]> {
    return this.find({
      where: {
        channel,
        context,
        is_active: true,
        is_deleted: false,
      } as any,
      order: { is_default: 'DESC', name: 'ASC' } as any,
    });
  }

  async findAllForAdmin(): Promise<CommunicationTemplateEntity[]> {
    return this.find({
      where: { is_deleted: false } as any,
      order: {
        channel: 'ASC',
        context: 'ASC',
        is_default: 'DESC',
        name: 'ASC',
      } as any,
    });
  }
}
