package production

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

type HeartbeatRepository struct{}

func (hr HeartbeatRepository) CreateHeartbeat(h *dto.Heartbeat) (*dto.Heartbeat, error) {
	ctx := context.Background()

	heartbeat, err := ProdQueries.CreateHeartbeat(ctx, postgres.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 := ProdQueries.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()
	heartbeat, err := ProdQueries.FindHeartbeatByUser(ctx, u.Identifier)
	if err != nil {
		return nil, pterror.Wrap(err, "Error finding heartbeat by user")
	}

	var ret []*dto.Heartbeat

	for _, h := range heartbeat {
		ret = append(ret, &dto.Heartbeat{
			Identifier: h.Identifier,
			User:       h.User,
			CreatedAt:  h.CreatedAt,
			IpAddr:     h.IpAddr,
			AuthToken:  h.AuthToken,
		})
	}

	return ret, nil
}
