package db

import (
	"context"
	"database/sql"
	"log/slog"
)

type Visit struct {
	db       *sql.DB
	log      *slog.Logger
	ID       int64 `json:"id"`
	Tgb_ID   int64 `json:"tgb_id"`
	Quantity int   `json:"quantity"`
	Edited   int64 `json:"edited"`
}

func NewVisits(db *sql.DB, log *slog.Logger) *Visit {
	log = log.With("obj", "Visits")
	return &Visit{db: db, log: log}
}

func (v Visit) Add(ctx context.Context, tgb_id int64) (bool, error) {
	stmt, err := v.db.PrepareContext(ctx,
		`
UPDATE visits
  SET quantity = quantity + 1,
      edited = strftime('%s','now')
                     WHERE tgb_id = ?;`)
	if err != nil {
		v.log.Error("prepare stmt", "error", err)
		return false, err
	}
	defer stmt.Close()
	_, err = stmt.ExecContext(ctx, tgb_id)
	if err != nil {
		v.log.Error("exec content", "error", err)
		return false, err
	}
	return true, nil
}
func (v Visit) Get(ctx context.Context, tgb_id int64) (*Visit, error) {
	stmt, err := v.db.PrepareContext(ctx, "SELECT id, tgb_id, quantity, edited FROM visits WHERE tgb_id = ?;")
	if err != nil {
		v.log.Error("prepare stmt", "error", err)
		return nil, err
	}
	defer stmt.Close()
	vi := &Visit{}
	if err := stmt.QueryRowContext(ctx, tgb_id).Scan(&v.ID, &v.Tgb_ID, &v.Quantity, &v.Edited); err != nil {
		v.log.Error("Query row", "error", err)
		return nil, err
	}

	return vi, nil
}
