import * as crypto from 'crypto';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import type { AdminUser } from '@prisma/client';

@Injectable()
export class AdminTokenService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
  ) {}

  async generateAccessToken(adminUser: AdminUser, sessionId: string): Promise<string> {
    const secret = this.configService.get<string>('jwt.adminSecret')!;
    const expiresIn = this.configService.get<string>('jwt.adminExpiresIn') || '1h';
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return this.jwtService.signAsync(
      { sub: adminUser.id, type: 'admin', role: adminUser.role, sessionId },
      { secret, expiresIn } as any,
    );
  }

  generateRefreshToken(): { token: string; hash: string } {
    const token = crypto.randomBytes(48).toString('hex');
    const hash = crypto.createHash('sha256').update(token).digest('hex');
    return { token, hash };
  }

  hashToken(token: string): string {
    return crypto.createHash('sha256').update(token).digest('hex');
  }
}
