import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

import { environment } from '../../environments/environment';

export type SystemTenantDto = {
  tenantId: string;
  nomeOficial: string;
};

export type ListSystemTenantsParams = {
  source?: string;
  active?: boolean;
};

export type CreateSystemTenantUserPayload = {
  name: string;
  email: string;
  password: string;
  roles: string[];
  clientCredentialsOnly?: boolean;
};

export type CreateSystemTenantUserResponse = {
  userId: string;
  tenantId: string;
  email: string;
  roles: string[];
};

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

  constructor(private http: HttpClient) {
    const raw = (environment.apiUrl || '').replace(/\/+$/, '');
    this.baseApi = raw.toLowerCase().endsWith('/api') ? raw : `${raw}/api`;
  }

  listTenants(params?: ListSystemTenantsParams): Observable<SystemTenantDto[]> {
    let httpParams = new HttpParams();
    if (params?.source) {
      httpParams = httpParams.set('source', params.source);
    }
    if (typeof params?.active === 'boolean') {
      httpParams = httpParams.set('active', String(params.active));
    }

    return this.http.get<SystemTenantDto[]>(`${this.baseApi}/system/tenants`, {
      params: httpParams,
    });
  }

  createTenantUser(
    tenantId: string,
    payload: CreateSystemTenantUserPayload
  ): Observable<CreateSystemTenantUserResponse> {
    return this.http.post<CreateSystemTenantUserResponse>(
      `${this.baseApi}/system/tenants/${tenantId}/users`,
      payload
    );
  }
}
