package crawler

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

	"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 bcd struct {
	client ports.DollarPort
}

func NewBCD(client ports.DollarPort) ports.APIPorts {
	return &bcd{
		client: client,
	}
}

func (b bcd) Scrape(ctx context.Context, page playwright.Page, log *slog.Logger) (insts []*domain.History, err error) {
	log = log.With("scrapper", "bcd")
	tout := 90000.00
	uri := os.Getenv("BCD")
	if _, err = page.Goto(uri, playwright.PageGotoOptions{
		Timeout:   &tout,
		WaitUntil: playwright.WaitUntilStateLoad,
	}); err != nil {
		log.Error("could not get info", "error", err)
		return nil, err
	}
	compraLocator := page.Locator("span#actualPurchaseValue")

	compraLocator.WaitFor(playwright.LocatorWaitForOptions{
		Timeout: &tout,
		State:   playwright.WaitForSelectorStateVisible,
	})

	ventaLocator := page.Locator("span#actualSellingValue")

	compra, err := compraLocator.TextContent()
	if err != nil {
		log.Error("locating compra", "err", err)
		return nil, err
	}
	venta, err := ventaLocator.TextContent()
	if err != nil {
		log.Error("locating venta", "err", err)
		return nil, err
	}

	inst := &domain.History{
		Parser: "bcd",
		Name:   "banco central dominicano",
		Parsed: time.Now().Unix(),
	}

	inst.Compra = helpers.Normalize(compra)
	inst.Venta = helpers.Normalize(venta)

	if inst.Compra == 0 || inst.Venta == 0 {
		return nil, fmt.Errorf("bcd: institution not parsed compra or venta cant be 0")
	}
	return []*domain.History{inst}, nil
}

func (bc bcd) ExecParser(
	ctx context.Context,
	browser *playwright.Browser,
	log *slog.Logger) (err error) {
	t := true
	ua := helpers.NewMobileUA()
	b := *browser
	page, err := b.NewPage(playwright.BrowserNewPageOptions{
		UserAgent: &ua,
		//	IsMobile:  &t,
		HasTouch: &t,
		Viewport: &playwright.Size{
			Width:  412,
			Height: 915,
		},
		Screen: &playwright.Size{
			Width:  412,
			Height: 915,
		},
	})
	if err != nil {
		log.Error("creating page", "error", err)
		os.Exit(1)
	}
	ctx, cancel := context.WithTimeout(ctx, 6*time.Minute)
	defer page.Close()
	defer cancel()
	inst, err := bc.Scrape(ctx, page, log)
	if err != nil {
		return err
	}
	err = bc.client.NewHistory(inst[0])

	if err != nil {
		return err
	}

	return err
}
