package crawler

import (
	"context"
	"fmt"
	"log/slog"
	"time"

	"github.com/maximotejeda/us_dop_scrapper/config"
	"github.com/maximotejeda/us_dop_scrapper/helpers"
	"github.com/maximotejeda/us_dop_scrapper/internal/application/core/domain"
	"github.com/maximotejeda/us_dop_scrapper/internal/ports"
	"github.com/playwright-community/playwright-go"
)

type bnc struct{}

func NewBNC() ports.APIPorts {
	return &bnc{}
}

func (bn bnc) Scrape(ctx context.Context, page playwright.Page, log *slog.Logger) (insts []*domain.History, err error) {
	tout := 120000.00
	log = log.With("scrapper", "bnc")
	if _, err := page.Goto(config.GetBNCURL(), playwright.PageGotoOptions{
		Timeout:   &tout,
		WaitUntil: playwright.WaitUntilStateLoad,
	}); err != nil {
		log.Error("could not get info", "error", err)
		return nil, err
	}

	currencyDiv := page.Locator(".calculator__content")
	currencyDiv.WaitFor()

	buyInput := page.Locator("div.calculator__buy-input:nth-child(2) > input:nth-child(2)")

	sellInput := page.Locator("div.calculator__sell-input:nth-child(2) > input:nth-child(2)")

	compraSTR, err := buyInput.InputValue()
	if err != nil {
		log.Error("could not get compra str", "err", err)
		return nil, err
	}
	ventaSTR, err := sellInput.InputValue()
	if err != nil {
		log.Error("could not get venta string", "err", err)
		return nil, err
	}
	inst := &domain.History{
		Name:   "banesco",
		Parser: "bnc",
		Parsed: time.Now().Unix(),
	}

	inst.Venta = helpers.Normalize(ventaSTR)
	inst.Compra = helpers.Normalize(compraSTR)

	if inst.Compra == 0 || inst.Venta == 0 {
		return nil, fmt.Errorf("bnc: institution not parsed: %v", inst)
	}
	return []*domain.History{inst}, nil
}
