package service

import (
	"context"
	"fmt"
	"git.gocasts.ir/ebhomengo/niki/domain/campaign/entity"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
	"git.gocasts.ir/ebhomengo/niki/types"
	"time"
)

func ToCampaignEntity(req CreateCampaignRequest) entity.Campaign {
	return entity.Campaign{
		Title:        req.Title,
		Description:  req.Description,
		Link:         req.Link,
		Slogan:       req.Slogan,
		GoalAmount:   req.GoalAmount,
		RaisedAmount: 0,
		Status:       types.CampaignStatus(req.Status),
		DeadlineAt:   req.DeadlineAt,
		AdminID:      req.AdminID,
		CreatedAt:    time.Now(),
	}
}

// CreateCampaign handles creation of a new campaign.
func (s *CampaignService) CreateCampaign(ctx context.Context, req CreateCampaignRequest) (types.ID, error) {
	const op = "service.campaign.create_campaign"

	if err := validateCreateCampaignRequest(req); err != nil {
		return 0, richerror.New(op).WithErr(err)
	}

	campaign := ToCampaignEntity(req)

	id, err := s.repo.Create(ctx, campaign)
	if err != nil {
		return 0, richerror.New(op).WithErr(err)
	}

	return id, nil
}

func validateCreateCampaignRequest(req CreateCampaignRequest) error {
	if req.Title == "" {
		return errRequired("title")
	}
	if req.GoalAmount <= 0 {
		return errInvalid("goal_amount must be greater than 0")
	}
	if req.AdminID == 0 {
		return errRequired("admin_id")
	}

	validStatuses := map[string]bool{
		"draft":     true,
		"active":    true,
		"completed": true,
		"cancelled": true,
		"paused":    true,
	}
	if !validStatuses[string(req.Status)] {
		return errInvalid("invalid status provided")
	}

	return nil
}

// --- Helpers ---
func errRequired(field string) error {
	return fmt.Errorf("%s is required", field)
}

func errInvalid(msg string) error {
	return fmt.Errorf(msg)
}
