package session

import (
	"context"
	"database/sql"
	"time"
)

type Row struct {
	ID        int64
	Token     string
	CreatedAt time.Time
	ExpiresAt time.Time
}

func QCreate(ctx context.Context, db *sql.DB, token string, expiresAt time.Time) (Row, error) {
	var row Row
	err := db.QueryRowContext(ctx, `
		INSERT INTO session (token, expires_at)
		VALUES ($1, $2)
		RETURNING id, token, created_at, expires_at
	`, token, expiresAt).Scan(&row.ID, &row.Token, &row.CreatedAt, &row.ExpiresAt)
	return row, err
}

func QFindByToken(ctx context.Context, db *sql.DB, token string) (*Row, error) {
	var row Row
	err := db.QueryRowContext(ctx, `
		SELECT id, token, created_at, expires_at
		FROM session
		WHERE token = $1
		LIMIT 1
	`, token).Scan(&row.ID, &row.Token, &row.CreatedAt, &row.ExpiresAt)
	if err == sql.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &row, nil
}

func QDelete(ctx context.Context, db *sql.DB, token string) error {
	_, err := db.ExecContext(ctx, `DELETE FROM session WHERE token = $1`, token)
	return err
}

func QDeleteExpired(ctx context.Context, db *sql.DB) error {
	_, err := db.ExecContext(ctx, `DELETE FROM session WHERE expires_at < NOW()`)
	return err
}
