package service

import (
	"context"
	"git.gocasts.ir/ebhomengo/niki/domain/authorization/entity"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)

type Authorization struct {
	roleRepo RoleRepo
}

func NewAuthorization(roleRepo RoleRepo) Authorization {
	return Authorization{roleRepo: roleRepo}
}

func (a Authorization) Store(ctx context.Context, req StoreRoleRequest) (entity.Role, error) {
	const op = "authorizationservice.Store"

	if err := a.validateStoreRole(req); err != nil {
		return entity.Role{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
	}

	role, err := a.roleRepo.Store(ctx, req)
	if err != nil {
		return entity.Role{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
	}
	return entity.Role{
		ID:       role,
		Title_fa: req.TitleFa,
		Title:    req.Title,
	}, nil
}

func (a Authorization) Update(ctx context.Context, req UpdateRoleRequest) (entity.Role, error) {
	const op = "authorizationservice.Update"

	if err := a.validateUpdateRole(ctx, req); err != nil {
		return entity.Role{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
	}

	role, err := a.roleRepo.Update(ctx, req)
	if err != nil {
		return entity.Role{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
	}

	return entity.Role{
		ID:       role,
		Title_fa: req.TitleFa,
		Title:    req.Title,
	}, nil
}
