package services

import (
	"context"
	"git.sch9.ru/new_gate/ms-tester/internal/lib"
	"git.sch9.ru/new_gate/ms-tester/internal/models"
)

type ContestStorage interface {
	CreateContest(ctx context.Context, contest *models.Contest) (int32, error)
	ReadContestById(ctx context.Context, id int32) (*models.Contest, error)
	UpdateContest(ctx context.Context, contest *models.Contest) error
	DeleteContest(ctx context.Context, id int32) error
}

type ContestService struct {
	contestStorage    ContestStorage
	permissionService IPermissionService
}

func NewContestService(
	contestStorage ContestStorage,
	permissionService IPermissionService,
) *ContestService {
	return &ContestService{
		contestStorage:    contestStorage,
		permissionService: permissionService,
	}
}

func (service *ContestService) CreateContest(ctx context.Context, contest *models.Contest) (int32, error) {
	if !service.permissionService.Allowed(ctx, extractUser(ctx), "create") {
		return 0, lib.ServiceError(nil, lib.ErrNoPermission, "permission denied")
	}
	return service.contestStorage.CreateContest(ctx, contest)
}

func (service *ContestService) ReadContestById(ctx context.Context, id int32) (*models.Contest, error) {
	if !service.permissionService.Allowed(ctx, extractUser(ctx), "read") {
		return nil, lib.ServiceError(nil, lib.ErrNoPermission, "permission denied")
	}
	return service.contestStorage.ReadContestById(ctx, id)
}

func (service *ContestService) UpdateContest(ctx context.Context, contest *models.Contest) error {
	if !service.permissionService.Allowed(ctx, extractUser(ctx), "update") {
		return lib.ServiceError(nil, lib.ErrNoPermission, "permission denied")
	}
	return service.contestStorage.UpdateContest(ctx, contest)
}

func (service *ContestService) DeleteContest(ctx context.Context, id int32) error {
	if !service.permissionService.Allowed(ctx, extractUser(ctx), "delete") {
		return lib.ServiceError(nil, lib.ErrNoPermission, "permission denied")
	}
	return service.contestStorage.DeleteContest(ctx, id)
}
