import { Injectable, UnauthorizedException } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { User, UserDocument } from '../schemas/user.schema.js'
import type { AuthentikJwtPayload } from './jwt-payload.interface.js'

// Resolves the JWT-authenticated identity into a Mongo User document. The JWT is
// just identity (sub); all authorization state — tenant memberships, platformAdmin —
// reads from the DB. Keeps the token small regardless of how many tenants a user
// belongs to.
@Injectable()
export class ActorService {
  constructor(@InjectModel(User.name) private readonly userModel: Model<UserDocument>) {}

  async resolve(jwt: AuthentikJwtPayload): Promise<UserDocument> {
    const user = await this.userModel.findOne({ authentikSubjectId: jwt.sub }).exec()
    if (!user) {
      // First login should always hit /users/me first, which upserts. If we get here
      // some other endpoint was called before any /users/me — surface as 401 so the
      // caller bootstraps the session.
      throw new UnauthorizedException('User record not yet provisioned — call /users/me first')
    }
    return user
  }
}
