import {Component, OnInit} from '@angular/core';
import {PortfolioService} from '../../services/portfolio.service';
import {Portfolio} from '../../models/portfolio.model';
import {FormsModule} from '@angular/forms';
import {NgClass} from '@angular/common';

@Component({
  selector: 'app-dashboard',
  imports: [
    FormsModule,
    NgClass
  ],
  templateUrl: './dashboard.component.html'
})
export class DashboardComponent implements OnInit {
  portfolios: Portfolio[] = [];
  newPortfolio = { name: '', domain: '' };
  uploading: { [key: number]: boolean } = {};

  constructor(private portfolioService: PortfolioService) {}

  ngOnInit(): void {
    this.loadPortfolios();
  }

  loadPortfolios() {
    this.portfolioService.getPortfolios().subscribe({
      next: (res) => this.portfolios = res.data || []
    });
  }

  create() {
    this.portfolioService.createPortfolio(this.newPortfolio).subscribe({
      next: () => {
        this.newPortfolio = { name: '', domain: '' };
        this.loadPortfolios();
      }
    });
  }

  uploadZip(event: Event, portfolioId: number) {
    const file = (event.target as HTMLInputElement).files?.[0];
    if (!file) return;

    this.uploading[portfolioId] = true;
    this.portfolioService.uploadZip(portfolioId, file).subscribe({
      next: () => {
        this.uploading[portfolioId] = false;
        this.loadPortfolios();
      },
      error: () => this.uploading[portfolioId] = false
    });
  }

  deploy( portfolioId: number){
    this.portfolioService.deploy(portfolioId).subscribe({});
  }
}
