import { BadRequestException, Injectable } from '@nestjs/common'
import { TenantsService } from '../../tenants/tenants.service.js'
import { EventTypesService } from '../event-types/event-types.service.js'
import { HostsService } from '../hosts/hosts.service.js'
import type { BookingContext } from '../bookings/bookings.service.js'

// Resolves the unauthenticated (tenantSlug, hostSlug, eventTypeSlug) triple into
// a fully-loaded BookingContext, and shapes the public-facing info payload (no
// internal ids, no PII). Only active hosts + event types are bookable.
@Injectable()
export class PublicSchedulingService {
  constructor(
    private readonly tenants: TenantsService,
    private readonly hosts: HostsService,
    private readonly eventTypes: EventTypesService,
  ) {}

  async resolveContext(tenantSlug: string, hostSlug: string, eventTypeSlug: string): Promise<BookingContext> {
    const tenant = await this.tenants.findOneBySlug(tenantSlug)
    const host = await this.hosts.getBySlug(tenant._id, hostSlug)
    if (!host.isActive) throw new BadRequestException('This booking page is not available.')
    const eventType = await this.eventTypes.getActiveBySlug(tenant._id, host._id, eventTypeSlug)
    return {
      tenant: { _id: tenant._id, slug: tenant.slug, name: tenant.name, brandColor: tenant.brandColor },
      host,
      eventType,
    }
  }

  // Public event-type + host info + tenant branding, for the booking page header.
  publicInfo(ctx: BookingContext) {
    return {
      branding: {
        tenantSlug: ctx.tenant.slug,
        name: ctx.tenant.name,
        brandColor: ctx.tenant.brandColor ?? null,
      },
      host: {
        slug: ctx.host.slug,
        displayName: ctx.host.displayName,
        timezone: ctx.host.timezone,
      },
      eventType: {
        slug: ctx.eventType.slug,
        title: ctx.eventType.title,
        description: ctx.eventType.description ?? null,
        durationMinutes: ctx.eventType.durationMinutes,
        locationType: ctx.eventType.locationType,
      },
    }
  }
}
