import { OAuthFindClientByIdService } from '@app/o-auth/client';
import { IamClientWithApplications, IIamClientReader } from '@bridges/iam/client/ports';
import { Injectable, NotFoundException } from '@nestjs/common';

@Injectable()
export class OAuthClientReaderAdapter implements IIamClientReader {
  constructor(private readonly findByIdService: OAuthFindClientByIdService) {}

  async findByIdWithApplications(id: string): Promise<IamClientWithApplications> {
    const client = await this.findByIdService.main(id, {
      include: [{ association: 'applications' }],
    });

    if (!client) {
      throw new NotFoundException({
        message: `OAuthClient with id: ${id}, not found`,
        translation: 'o-auth.error.clientNotFound',
        placeholders: { id },
      });
    }

    const applications =
      (client as { applications?: { code?: string | null }[] }).applications ?? [];

    return {
      id: client.id,
      applicationCodes: applications
        .map((application) => application?.code)
        .filter((code): code is string => Boolean(code)),
    };
  }
}
