import { Injectable } from '@nestjs/common';
import { DatabaseService, logger } from '../../config';
import { DEFAULT_ORG_TIMEZONE } from './timezone.constants';
import { normalizeTimezone } from './timezone.util';

const CACHE_TTL_MS = 60_000;

type CacheEntry = {
  timezone: string;
  expiresAt: number;
};

@Injectable()
export class OrgTimezoneService {
  private readonly cache = new Map<string, CacheEntry>();

  constructor(private readonly db: DatabaseService) {}

  invalidate(ownerId: string): void {
    this.cache.delete(ownerId);
  }

  async getTimezone(ownerId: string): Promise<string> {
    const cached = this.cache.get(ownerId);
    if (cached && cached.expiresAt > Date.now()) {
      return cached.timezone;
    }

    try {
      const schedule = await this.db.working_schedule.findFirst({
        where: { owner_id: ownerId, status: 'active' },
        select: { timezone: true },
      });

      const timezone = normalizeTimezone(schedule?.timezone);
      this.cache.set(ownerId, {
        timezone,
        expiresAt: Date.now() + CACHE_TTL_MS,
      });

      return timezone;
    } catch (error) {
      logger.error(`Failed to resolve org timezone for ${ownerId}: ${String(error)}`);
      return DEFAULT_ORG_TIMEZONE;
    }
  }
}
