package adminseederservice

import (
	"context"
	"strconv"

	"git.gocasts.ir/ebhomengo/niki/entity"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
	"github.com/brianvoe/gofakeit/v7"
)

func (s Service) AddBenefactor(ctx context.Context) (entity.Benefactor, error) {
	const op = "adminseederservice.AddBenefactor"
	phoneNumber, pErr := s.getPhoneNumber(ctx)
	if pErr != nil {
		return entity.Benefactor{}, richerror.New(op).WithErr(pErr).WithKind(richerror.KindUnexpected)
	}

	benefactor, cErr := s.benefactorRepo.CreateBenefactor(ctx, entity.Benefactor{
		FirstName:   gofakeit.FirstName(),
		LastName:    gofakeit.LastName(),
		PhoneNumber: phoneNumber,
	})
	if cErr != nil {
		return entity.Benefactor{}, richerror.New(op).WithErr(cErr).WithKind(richerror.KindUnexpected)
	}

	return benefactor, nil
}

func (s Service) getPhoneNumber(ctx context.Context) (string, error) {
	minNum := 111111111
	maxNum := 999999999
	phoneNumber := "09" + strconv.Itoa(gofakeit.Number(minNum, maxNum))

	_, _, err := s.benefactorRepo.IsExistBenefactorByPhoneNumber(ctx, phoneNumber)
	if err != nil {
		return "", err
	}
	return phoneNumber, nil
}

func (s Service) getAddress(ctx context.Context, benefactorID uint) (entity.Address, error) {
	cities, cErr := s.addressRepo.GetAllCities(ctx)
	if cErr != nil {
		return entity.Address{}, cErr
	}

	city := cities[gofakeit.Number(1, 470)]
	address, aErr := s.addressRepo.CreateBenefactorAddress(ctx, entity.Address{
		PostalCode:   gofakeit.Zip(),
		Address:      gofakeit.Address().Address,
		Name:         gofakeit.Name(),
		Lat:          gofakeit.Latitude(),
		Lon:          gofakeit.Longitude(),
		CityID:       city.ID,
		ProvinceID:   city.ProvinceID,
		BenefactorID: benefactorID,
	})
	if aErr != nil {
		return entity.Address{}, aErr
	}

	return address, nil
}
