import { computed, inject, Injectable, resource, signal } from '@angular/core'
import { DefaultService, SaveSettingsRequest } from '@api-client/angular'
import { HotToastService } from '@ngxpert/hot-toast'
import { finalize, lastValueFrom } from 'rxjs'

interface SettingsUpdateOptions {
	showAutoApproveReservationEnabledToast: boolean
}

@Injectable({ providedIn: 'root' })
export class SettingsStore {
	private readonly _apiService = inject(DefaultService)
	private readonly _toast = inject(HotToastService)

	private readonly settingsResource = resource({
		loader: () => lastValueFrom(this._apiService.settingsControllerFind()),
	})
	private readonly timezoneListResource = resource({
		loader: () => lastValueFrom(this._apiService.staticControllerGetTimezones()),
	})

	readonly settings = this.settingsResource.value

	readonly isLoading = this.settingsResource.isLoading
	readonly isUpdating = signal(false)

	readonly timezone = computed(() => {
		return this.settingsResource.value()?.restaurant.timezone
	})

	readonly timezoneOffset = computed(() => {
		const settings = this.settingsResource.value()
		if (!settings) return

		return this.timezoneListResource.value()?.find((timezone) => timezone.code === settings.restaurant.timezone)?.offset
	})

	async updateSettings(settings: Partial<SaveSettingsRequest>, options?: Partial<SettingsUpdateOptions>) {
		this.isUpdating.set(true)

		await lastValueFrom(
			this._apiService.settingsControllerSave(settings).pipe(
				this._toast.observe({
					loading: 'Updating settings',
					success: 'Settings updated',
					error: 'Failed to update settings',
				}),
				finalize(() => this.isUpdating.set(false)),
			),
		)

		this.settingsResource.reload()

		if (options?.showAutoApproveReservationEnabledToast && settings.reservation?.autoApproveReservations.enabled) {
			this._toast.info(
				'Auto approving reservations has been enabled. You use change limits from Settings --> Reservations',
			)
		}
	}
}
