package repository

import (
	"context"
	"time"

	dbgen "Yimaru-Backend/gen/db"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
	// "golang.org/x/net/websocket"
)

type Store struct {
	queries *dbgen.Queries
	conn    *pgxpool.Pool
}

func NewStore(conn *pgxpool.Pool) *Store {

	queries := dbgen.New(conn)
	return &Store{
		queries: queries,
		conn:    conn,
	}
}

func OpenDB(url string) (*pgxpool.Pool, func(), error) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	conn, err := pgxpool.New(ctx, url)
	if err != nil {
		return nil, func() {}, err
	}

	if err := conn.Ping(ctx); err != nil {
		return nil, func() {}, err
	}

	return conn, func() {
		conn.Close()
	}, nil
}

func (s *Store) BeginTx(ctx context.Context) (*dbgen.Queries, pgx.Tx, error) {
	tx, err := s.conn.Begin(ctx)
	if err != nil {
		return nil, nil, err
	}
	q := s.queries.WithTx(tx)
	return q, tx, nil
}

// func (s *Store) ConnectWebSocket(ctx context.Context, recipientID int64, c *websocket.Conn) error {
// 	// Implement WebSocket connection logic
// 	return nil
// }

// func (s *Store) DisconnectWebSocket(recipientID int64) {
// 	// Implement WebSocket disconnection logic
// }
