package server

import (
	"context"

	"code.justin.tv/live/plucky/api/rpc"
	"github.com/twitchtv/twirp"
)

func (s *Server) GetOccurrences(ctx context.Context, request *rpc.GetOccurrencesRequest) (*rpc.GetOccurrencesResponse, error) {
	if request == nil {
		return nil, twirp.RequiredArgumentError("GetOccurrencesRequest")
	}

	serviceID := request.ServiceId
	if serviceID == "" {
		return nil, twirp.RequiredArgumentError("ServiceId")
	}
	stageID := request.StageId
	if stageID == "" {
		return nil, twirp.RequiredArgumentError("StageId")
	}

	service, err := s.getService(serviceID, stageID)
	if err != nil {
		return nil, err
	}

	fingerprint := request.Fingerprint
	if fingerprint == "" {
		return nil, twirp.RequiredArgumentError("Fingerprint")
	}

	startTime := s.clock.NowUTC()

	queryRange, err := getQueryRange(request.Start, request.End)
	if err != nil {
		return nil, err
	}

	err = s.updateDatabase(ctx, service, queryRange, request.SkipPartialDataRefetch)
	if err != nil {
		s.logger.Error(err)
		return nil, err
	}

	occurrences, err := s.database.GetOccurrencesByFingerprint(ctx, serviceID, fingerprint, queryRange)
	if err != nil {
		s.logger.Error(err)
		return nil, err
	}

	trendPoints, err := s.database.GetDayTrendPoints(ctx, serviceID, fingerprint, queryRange)
	if err != nil {
		s.logger.Error(err)
		return nil, err
	}

	endTime := s.clock.NowUTC()
	queryTimeMs := int32(endTime.Sub(startTime).Milliseconds())

	return &rpc.GetOccurrencesResponse{
		Fingerprint: fingerprint,
		Occurrence:  occurrences,
		TrendDay: &rpc.Trend{
			Points:     trendPoints,
			BucketSize: 60 * 60,
		},
		QueryTimeMs: queryTimeMs,
	}, nil
}
