import type { BackofficeLoginRateLimiter } from '../domain/ports.js';

/**
 * Backoffice login rate limiter (in-memory).
 * Stricter than the storefront: backoffice is a higher-value target.
 * 5 attempts per 15-minute window per email+IP.
 */
interface Bucket {
  count: number;
  resetAt: number;
}

const WINDOW_MS = 15 * 60 * 1000;
const MAX_ATTEMPTS = 5;

export class InMemoryBackofficeLoginRateLimiter implements BackofficeLoginRateLimiter {
  private readonly buckets = new Map<string, Bucket>();

  hit(key: string): { allowed: boolean; retryAfterMs: number; remaining: number } {
    const now = Date.now();
    const bucket = this.buckets.get(key);
    if (!bucket || bucket.resetAt < now) {
      this.buckets.set(key, { count: 1, resetAt: now + WINDOW_MS });
      return { allowed: true, retryAfterMs: 0, remaining: MAX_ATTEMPTS - 1 };
    }
    bucket.count++;
    const allowed = bucket.count <= MAX_ATTEMPTS;
    return {
      allowed,
      retryAfterMs: allowed ? 0 : bucket.resetAt - now,
      remaining: Math.max(0, MAX_ATTEMPTS - bucket.count),
    };
  }
}
