package scout

import (
	"context"
	"encoding/json"

	"apps/backend/internal/middleware"
	scoutDomain "apps/backend/internal/module/scout/domain"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *RunScanLogic) RunScan(req *types.ScoutScanReq) (*types.ScoutScanJobData, error) {
	if l.svcCtx.Jobs == nil || l.svcCtx.Scout == nil {
		return nil, response.Biz(503, 503001, "jobs module not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	if req == nil {
		return nil, response.Biz(400, 400020, "invalid scout scan request")
	}

	brief := types.BriefToDomain(&req.Brief)
	run, err := l.svcCtx.Scout.CreateQueuedRun(l.ctx, uid, brief)
	if err != nil {
		return nil, err
	}
	// Embed run_id alongside the immutable brief fields. The current worker can
	// still unmarshal the legacy flat RunBrief; the lifecycle worker will verify
	// run_id against Job.RefID.
	payload, err := json.Marshal(struct {
		RunID string `json:"run_id"`
		*scoutDomain.RunBrief
	}{RunID: run.ID, RunBrief: brief})
	if err != nil {
		_ = l.svcCtx.Scout.FailRun(l.ctx, uid, run.ID, "failed to encode scan payload")
		return nil, err
	}
	j, err := l.svcCtx.Jobs.ScheduleScoutScan(l.ctx, uid, run.ID, string(payload))
	if err != nil {
		_ = l.svcCtx.Scout.FailRun(l.ctx, uid, run.ID, "scan job scheduling failed")
		return nil, err
	}
	bound, err := l.svcCtx.Scout.BindRunJob(l.ctx, uid, run.ID, j.ID)
	if err != nil {
		_ = l.svcCtx.Jobs.Delete(l.ctx, uid, j.ID)
		_ = l.svcCtx.Scout.FailRun(l.ctx, uid, run.ID, "scan run/job binding failed")
		return nil, err
	}
	return &types.ScoutScanJobData{Job: types.JobFromModel(j), Run: types.ScoutRunFromDomain(bound)}, nil

}
