package seed

import (
	"context"
	"testing"
	"time"

	"git.gocasts.ir/ebhomengo/niki/entity"
	"git.gocasts.ir/ebhomengo/niki/repository/mysql"
	"github.com/brianvoe/gofakeit/v6"
	"github.com/stretchr/testify/assert"
)

//nolint
func CreateBenefactor(t *testing.T, db *mysql.DB) (*entity.Benefactor, func()) {
	t.Helper()
	benefactor := &entity.Benefactor{
		FirstName:   gofakeit.FirstName(),
		LastName:    gofakeit.LastName(),
		PhoneNumber: gofakeit.Phone(),
		Address:     gofakeit.Address().Address,
		Description: "",
		Email:       gofakeit.Email(),
		City:        gofakeit.City(),
		Gender:      0,
		Status:      entity.BenefactorActiveStatus,
		Birthdate:   time.Time{},
		Role:        entity.UserBenefactorRole,
	}
	ctx := context.Background()
	res, err := db.Conn().ExecContext(ctx, `insert into benefactors(phone_number, status, role) values(?, ?, ?)`,
		benefactor.PhoneNumber, benefactor.Status.String(), benefactor.Role.String())
	assert.Nil(t, err)
	//nolint
	id, _ := res.LastInsertId()
	benefactor.ID = uint(id)

	return benefactor, func() {
		_, err := db.Conn().ExecContext(ctx, `delete from benefactors where id=?`,
			id)
		assert.Nil(t, err)
	}
}

//nolint
func CreateAddress(t *testing.T, db *mysql.DB, benfactorID uint) (*entity.Address, func()) {
	t.Helper()
	address := &entity.Address{
		PostalCode: gofakeit.Address().Zip,
		Address:    gofakeit.Address().Address,
		Lat:        float32(gofakeit.Address().Latitude),
		Lon:        float32(gofakeit.Address().Longitude),
		//nolint
		CityID: 1,
		//nolint
		ProvinceID:   15,
		BenefactorID: benfactorID,
	}
	ctx := context.Background()
	res, err := db.Conn().ExecContext(ctx, `insert into addresses(postal_code, address, lat, lon,province_id,city_id,benefactor_id) values(?, ?, ?,?,?,?,?)`,
		address.PostalCode, address.Address, address.Lat, address.Lon, address.ProvinceID, address.CityID, address.BenefactorID)
	assert.Nil(t, err)
	//nolint
	// error is always nil
	id, _ := res.LastInsertId()
	address.ID = uint(id)

	return address, func() {
		_, err := db.Conn().ExecContext(ctx, `delete from addresses where id=?`,
			id)
		assert.Nil(t, err)
	}
}

func DeleteBenefactor(t *testing.T, db *mysql.DB, kindBoxReqID uint) {
	t.Helper()
	_, mErr := db.Conn().Exec(`delete from kind_box_reqs where id=?`, kindBoxReqID)
	assert.Nil(t, mErr)
}
