package api

import (
	"context"
	"github.com/maximotejeda/us_dop_scrapper/helpers"
	"github.com/maximotejeda/us_dop_scrapper/internal/ports"
	"log/slog"
)

type Application struct {
	log *slog.Logger
	api ports.APIPorts
}

func NewApplication(crawler ports.APIPorts) *Application {
	log := slog.Default()
	log = log.With("application", "root")
	return &Application{
		log: log,
		api: crawler,
	}
}

func (a Application) Run() {
	ctx := context.Background()
	ch, ff, wk := helpers.CreateBrowser(a.log)
	err := a.api.ExecParser(ctx, ch, a.log)
	if err != nil {
		a.log.Info("failed on frist browser", "browser", "chrome", "error", err)
		err := a.api.ExecParser(ctx, ff, a.log)
		if err != nil {
			a.log.Error("failed on second browser", "browser", "firefox", "error", err)
			err := a.api.ExecParser(ctx, wk, a.log)
			if err != nil {
				a.log.Error("tried all browsers error", "brwser", "webkit", "error", err)
			}
		}
	}
}
