package mysql

import (
	"context"
	"git.gocasts.ir/ebhomengo/niki/donate_app/service/entity"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
	"git.gocasts.ir/ebhomengo/niki/repository/mysql"
	"git.gocasts.ir/ebhomengo/niki/types"
)

type DB struct {
	conn *mysql.DB
}

func New(db *mysql.DB) *DB {
	return &DB{conn: db}
}

// Create adds a new participant to a campaign
func (d *DB) CreateCampaignParticipants(ctx context.Context, participant entity.CampaignParticipant) (types.ID, error) {
	const Op = "repository.mysql.campaign_participant.create"

	tx, err := d.conn.Conn().BeginTx(ctx, nil)
	if err != nil {
		return 0, richerror.New(Op).WithErr(err)
	}
	defer tx.Rollback()

	query := `INSERT INTO campaign_participants (id,campaign_id, user_id, amount , created_at) 
              VALUES (?, ?, ? , ? , NOW())`

	result, err := tx.ExecContext(ctx, query,
		participant.ID,
		participant.CampaignID,
		participant.UserID,
		participant.Amount,
		participant.CreatedAt,
	)

	if err != nil {
		return 0, richerror.New(Op).WithErr(err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return 0, richerror.New(Op).WithErr(err)
	}
	if err := tx.Commit(); err != nil {
		return 0, richerror.New(Op).WithErr(err)
	}

	return types.ID(id), nil

}
