package copy_mission

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	missionentity "haixun-backend/internal/model/copy_mission/domain/entity"
	missiondomain "haixun-backend/internal/model/copy_mission/domain/usecase"
	jobdom "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateCopyMissionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateCopyMissionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateCopyMissionLogic {
	return &UpdateCopyMissionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateCopyMissionLogic) UpdateCopyMission(req *types.UpdateCopyMissionHandlerReq) (*types.CopyMissionData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	patch := toMissionPatch(&req.UpdateCopyMissionReq)
	if req.Status != nil {
		status := strings.TrimSpace(*req.Status)
		if status != string(missionentity.StatusArchived) && status != string(missionentity.StatusOpen) {
			return nil, app.For(code.Persona).InputMissingRequired("status 僅支援 archived 或 open")
		}
		st := missionentity.Status(status)
		patch.Status = &st
	}
	item, err := l.svcCtx.CopyMission.Update(l.ctx, missiondomain.UpdateRequest{
		TenantID:  tenantID,
		OwnerUID:  uid,
		PersonaID: strings.TrimSpace(req.PersonaID),
		MissionID: strings.TrimSpace(req.ID),
		Patch:     patch,
	})
	if err != nil {
		return nil, err
	}
	if req.Status != nil && strings.TrimSpace(*req.Status) == string(missionentity.StatusArchived) {
		if schedule, err := findCopyMissionScanSchedule(l.ctx, l.svcCtx, strings.TrimSpace(req.ID)); err == nil && schedule != nil && schedule.Enabled {
			disabled := false
			_, _ = l.svcCtx.Job.UpdateSchedule(l.ctx, jobdom.UpdateScheduleRequest{
				ID:      schedule.ID.Hex(),
				Enabled: &disabled,
			})
		}
	}
	data := toCopyMissionData(*item)
	return &data, nil
}
