import { Component } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {environment} from "../../environments/environment";
import {NgIf} from "@angular/common";
import {CuteLoadingComponent} from "../../corelib/components/cute-loading/cute-loading.component";
import {UserService} from "../../corelib/service/user.service";
import {Router} from "@angular/router";

interface CreateMetabaseUserResponse {
  email: string;
  password: string;
}

interface GetMetabaseUserResponse {
  email: string;
}

@Component({
  selector: 'app-metabase',
  standalone: true,
  imports: [
    NgIf,
    CuteLoadingComponent
  ],
  templateUrl: './metabase.component.html',
  styleUrl: './metabase.component.css'
})
export class MetabaseComponent {

  isLoading: boolean = true;
  user: GetMetabaseUserResponse | null = null;
  createResponse: CreateMetabaseUserResponse | null = null;

  constructor(private httpClient: HttpClient, private userService: UserService, private router: Router) { }

  ngOnInit() {
    this.userService.isAdmin().then(isAdmin => {
      if (!isAdmin) {
        this.router.navigate(['/']);
      } else {
        this.getUser();
      }
    }).catch(() => {
      this.router.navigate(['/']);
    });
  }

  resetPassword() {
    this.httpClient.get<CreateMetabaseUserResponse>(`${environment.apiUrl}/metabase/reset`, { withCredentials: true })
      .subscribe({
        next: (data) => {
          this.createResponse = data;
        },
        error: () => {
          this.createResponse = null;
        }
      });
  }

  getUser() {
    this.httpClient.get<GetMetabaseUserResponse>(`${environment.apiUrl}/metabase/status`, { withCredentials: true })
      .subscribe({
        next: (data) => {
          this.user = data;
          this.isLoading = false;
        },
        error: () => {
          this.user = null;
          this.isLoading = false;
        }
      });
  }

  createNewUser() {
    this.httpClient.get<CreateMetabaseUserResponse>(`${environment.apiUrl}/metabase/create`, { withCredentials: true })
      .subscribe({
        next: (data) => {
          this.createResponse = data;
        },
        error: () => {
          this.createResponse = null;
        }
      });
  }

}
