import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { RouterModule, Router } from '@angular/router';
import { Questionario } from '../../../models/questionario.model';
import { QuestionarioService } from '../../../services/questionario.service';
import { AuthService, User } from '../../../services/auth.service';

@Component({
  selector: 'app-listarQuestionario',
  standalone: true,
  imports: [
    FormsModule,
    CommonModule,
    RouterModule,
  ],
  templateUrl: './listarQuestionario.component.html',
  styleUrls: ['./listarQuestionario.component.css']
})


export class ListarQuestionariosComponent implements OnInit {
  questionarios: Questionario[] = [];


  constructor(
    private router: Router,
    private questionarioService: QuestionarioService,
    private authService: AuthService
  ) { }

  ngOnInit(): void {
    const funcId = this.getFuncionarioIdLogado();
    if (typeof funcId === 'number') {
      this.questionarioService.listarQuestionariosPorFuncionario(funcId).subscribe({
        next: (data: Questionario[]) => {
          this.questionarios = data;
        },
        error: (err) => {
          console.error('Erro ao buscar questionários', err);
        }
      });
    } else {
      console.error('Funcionário não está logado ou ID inválido');
    }
  }

  responderQuestionario(id: number): void {
    this.router.navigate(['/responder'], { queryParams: { id } });
  }

  // ver se lleo sabe pegar esse valor pelo cookies
  private getFuncionarioIdLogado(): number | undefined {
    let userId: number | undefined;
    this.authService.currentUser.subscribe((user) => {
      userId = user?.id;
    }).unsubscribe();
    return userId;
  }
}
