import { CACHE_MANAGER, Cache } from '@nestjs/cache-manager'
import { ForbiddenException, Inject, Injectable } from '@nestjs/common'
import { SessionStore } from '@backend/auth'
import { TableRepository } from '@backend/repository'
import { TableGraphMapper } from '../mappers'
import { TableGraphResponse } from '../types'
import { TableGraph, TableGraphBuilder } from './table-graph'

const CACHE_KEY_PREFIX = 'TABLE_GRAPH'

@Injectable()
export class TableGraphService {
	constructor(
		private readonly _tableRepository: TableRepository,
		@Inject(CACHE_MANAGER) private readonly _cacheManager: Cache,
	) {}

	async getGraph(): Promise<TableGraphResponse> {
		const tenantId = SessionStore.tenantId
		if (!tenantId) throw new ForbiddenException()

		const cacheKey = this.getCacheKey(tenantId)

		const cachedGraph = await this._cacheManager.get<TableGraphResponse>(cacheKey)
		if (cachedGraph) return cachedGraph

		const graph = await this.buildGraph()
		const response = TableGraphMapper.entityToResponse(graph)
		await this._cacheManager.set(cacheKey, response)

		return response
	}

	private async buildGraph(): Promise<TableGraph> {
		const tables = await this._tableRepository.find()
		const graph = new TableGraphBuilder().build(tables)

		return graph
	}

	async invalidateCache(tenantId: string): Promise<void> {
		await this._cacheManager.del(this.getCacheKey(tenantId))
	}

	private getCacheKey(tenantId: string): string {
		return `${CACHE_KEY_PREFIX}_${tenantId}`
	}
}
