package mysql

import (
	"context"
	"git.gocasts.ir/ebhomengo/niki/domain/campaign/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}
}

// CreateCampaign creates a new campaign
func (d *DB) CreateAndSave(ctx context.Context, campaign entity.Campaign) (types.ID, error) {
	const Op = "repository.mysql.campaign.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 campaigns (title, description, goal_amount, raised_amount,
        status, deadline_at ,admin_id , created_at ) 
        VALUES (?, ?, ?, ?, ?, ?, ? , NOW() )`

	result, err := tx.ExecContext(ctx, query,
		campaign.Title,
		campaign.Description,
		campaign.GoalAmount,
		campaign.RaisedAmount,
		campaign.Status,
		campaign.DeadlineAt,
		campaign.AdminID,
		campaign.CreatedAt,
	)
	if err != nil {
		return 0, richerror.New(Op).WithErr(err)
	}

	campaignID, 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(campaignID), nil
}
