package development

import (
	"context"
	"git.markbailey.dev/cervers/ptpp/lib/database/dto"
	pterror "git.markbailey.dev/cervers/ptpp/lib/error"
	"git.markbailey.dev/cervers/ptpp/models/sqlite"
)

type HeartbeatRepository struct{}

func (hr HeartbeatRepository) CreateHeartbeat(h *dto.Heartbeat) (*dto.Heartbeat, error) {
	ctx := context.Background()
	heartbeat, err := TestQueries.CreateHeartbeat(ctx, sqlite.CreateHeartbeatParams{
		User:      h.User,
		CreatedAt: &h.CreatedAt,
		IpAddr:    h.IpAddr,
		AuthToken: h.AuthToken,
	})
	if err != nil {
		return nil, pterror.Wrap(err, "Error creating heartbeat")
	}

	return &dto.Heartbeat{
		Identifier: heartbeat.Identifier,
		User:       heartbeat.User,
		CreatedAt:  *heartbeat.CreatedAt,
		IpAddr:     heartbeat.IpAddr,
		AuthToken:  heartbeat.AuthToken,
	}, nil
}

func (hr HeartbeatRepository) FindHeartbeatByID(id int64) (*dto.Heartbeat, error) {
	ctx := context.Background()
	heartbeat, err := TestQueries.FindHeartbeatByID(ctx, id)
	if err != nil {
		return nil, pterror.Wrap(err, "Error finding heartbeat by ID")
	}

	return &dto.Heartbeat{
		Identifier: heartbeat.Identifier,
		User:       heartbeat.User,
		CreatedAt:  *heartbeat.CreatedAt,
		IpAddr:     heartbeat.IpAddr,
		AuthToken:  heartbeat.AuthToken,
	}, err
}

func (hr HeartbeatRepository) FindHeartbeatByUser(u dto.User) ([]*dto.Heartbeat, error) {
	ctx := context.Background()
	heartbeats, err := TestQueries.FindHeartbeatByUser(ctx, u.Identifier)
	if err != nil {
		return nil, pterror.Wrap(err, "Error finding heartbeats by user")
	}

	var ret []*dto.Heartbeat
	for _, h := range heartbeats {
		ret = append(ret, &dto.Heartbeat{
			Identifier: h.Identifier,
			User:       h.User,
			CreatedAt:  *h.CreatedAt,
			IpAddr:     h.IpAddr,
			AuthToken:  h.AuthToken,
		})
	}

	return ret, nil
}
