package copy_mission

import (
	"context"

	jobentity "haixun-backend/internal/model/job/domain/entity"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

const viralScanTemplate = "scan-viral"

func findCopyMissionScanSchedule(ctx context.Context, svcCtx *svc.ServiceContext, missionID string) (*jobentity.Schedule, error) {
	schedules, _, _, _, _, err := svcCtx.Job.ListSchedules(ctx, "copy_mission", missionID, 1, 50)
	if err != nil {
		return nil, err
	}
	for _, schedule := range schedules {
		if schedule != nil && schedule.TemplateType == viralScanTemplate {
			return schedule, nil
		}
	}
	return nil, nil
}

func toCopyMissionScanScheduleData(schedule *jobentity.Schedule, personaID, missionID string) *types.CopyMissionScanScheduleData {
	if schedule == nil {
		return &types.CopyMissionScanScheduleData{
			PersonaID: personaID,
			MissionID: missionID,
			Cron:      "0 9 * * *",
			Timezone:  "Asia/Taipei",
			Enabled:   false,
		}
	}
	data := &types.CopyMissionScanScheduleData{
		ID:        schedule.ID.Hex(),
		PersonaID: personaID,
		MissionID: missionID,
		Cron:      schedule.Cron,
		Timezone:  schedule.Timezone,
		Enabled:   schedule.Enabled,
		NextRunAt: schedule.NextRunAt,
	}
	if schedule.LastRunAt != nil {
		data.LastRunAt = *schedule.LastRunAt
	}
	return data
}
