import { SessionStore, TenantHeaderInterceptor } from '@backend/auth'
import { SettingsRepository } from '@backend/repository'
import { BadRequestException, Controller, Get, Logger, UseInterceptors } from '@nestjs/common'
import { ApiBadRequestResponse, ApiInternalServerErrorResponse, ApiOkResponse, ApiTags } from '@nestjs/swagger'
import { SettingsMapper } from '../mappers'
import { CustomerAppSettings, WidgetSettingsResponse } from '../types'

@UseInterceptors(TenantHeaderInterceptor)
@Controller('customer/settings')
@ApiTags('customer')
export class CustomerSettingsController {
	private readonly logger = new Logger(CustomerSettingsController.name)

	constructor(private readonly _settingsRepository: SettingsRepository) {}

	@Get('app')
	@ApiOkResponse({ type: CustomerAppSettings })
	@ApiBadRequestResponse()
	@ApiInternalServerErrorResponse()
	async findAppSettings(): Promise<CustomerAppSettings> {
		const settings = await this._settingsRepository.findOne({
			select: { customerApp: {} },
		})
		if (!settings) {
			throw new BadRequestException('Tenant has not set app settings')
		}

		return SettingsMapper.entityToResponse(settings).customerApp
	}

	@Get('widget')
	@ApiOkResponse({ type: WidgetSettingsResponse })
	@ApiBadRequestResponse()
	@ApiInternalServerErrorResponse()
	async findWidgetSettings(): Promise<WidgetSettingsResponse> {
		const settings = await this._settingsRepository.findOne({
			select: { customerApp: {}, schedule: {}, reservation: {}, restaurant: {} },
		})

		if (!settings) {
			this.logger.error(`Settings for tenant ${SessionStore.tenantId} not found`)
			throw new BadRequestException()
		}

		return SettingsMapper.entityToWidgetSettings(settings)
	}
}
