package crawler

import (
	"context"
	"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 vimenca struct{}

func NewVimenca() ports.APIPorts {
	return &vimenca{}
}

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

	currencyTable := page.Locator(".bns--table")
	currencyTable.WaitFor()

	infoContainer := page.Locator(".layout-uikit > div:nth-child(1)")

	buyInfo := infoContainer.Locator(".purchaseValue")
	sellInfo := infoContainer.Locator(".saleValue")

	compraSTR, err := buyInfo.InnerText()
	if err != nil {
		log.Error("could not get compra str", "err", err)
		return nil, err
	}

	ventaSTR, err := sellInfo.InnerText()
	if err != nil {
		log.Error("could not get venta string", "err", err)
		return nil, err
	}
	inst := &domain.History{
		Name:   "banco vimenca",
		Parser: "vimenca",
		Parsed: time.Now().Unix(),
	}

	inst.Venta = helpers.Normalize(ventaSTR)
	inst.Compra = helpers.Normalize(compraSTR)
	log.Info("institution", "value", inst)
	return []*domain.History{inst}, nil
}
