import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ApiConfigService } from '../../../core/services/api-config.service';

export interface CreateInvitationResult {
  /** Raw, single-use token — returned once; build the link from it client-side. */
  token: string;
  /** ISO timestamp when the link stops working. */
  expiresAt: string;
}

@Injectable({ providedIn: 'root' })
export class InvitationApiService {
  private readonly endpoint: string;

  constructor(private http: HttpClient, apiConfig: ApiConfigService) {
    this.endpoint = apiConfig.getApiUrl('invitations');
  }

  /** Generate (or re-issue) a first-login invitation link for a member. */
  create(memberId: number, email?: string): Observable<CreateInvitationResult> {
    return this.http.post<CreateInvitationResult>(this.endpoint, { memberId, email });
  }

  /** E-mail an already-generated link to the member. */
  sendEmail(memberId: number, link: string): Observable<void> {
    return this.http.post<void>(`${this.endpoint}/send`, { memberId, link });
  }
}
