package persona

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/library/threadspost"
	copydraftdomain "haixun-backend/internal/model/copy_draft/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

type UpdatePersonaCopyDraftLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdatePersonaCopyDraftLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePersonaCopyDraftLogic {
	return &UpdatePersonaCopyDraftLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *UpdatePersonaCopyDraftLogic) UpdatePersonaCopyDraft(
	req *types.UpdateCopyDraftHandlerReq,
) (*types.CopyDraftData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.ID)
	draftID := strings.TrimSpace(req.DraftID)
	if _, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID); err != nil {
		return nil, err
	}
	if req.Text != nil {
		if err := threadspost.ValidatePublish(*req.Text); err != nil {
			return nil, app.For(code.Persona).InputInvalidFormat(err.Error())
		}
	}

	updated, err := l.svcCtx.CopyDraft.Update(l.ctx, copydraftdomain.UpdateRequest{
		TenantID:  tenantID,
		OwnerUID:  uid,
		PersonaID: personaID,
		DraftID:   draftID,
		Patch: copydraftdomain.CopyDraftPatch{
			Text:   req.Text,
			Hook:   req.Hook,
			Angle:  req.Angle,
			Status: req.Status,
		},
	})
	if err != nil {
		return nil, err
	}
	data := types.CopyDraftData{
		ID:                 updated.ID,
		PersonaID:          updated.PersonaID,
		CopyMissionID:      updated.CopyMissionID,
		ScanPostID:         updated.ScanPostID,
		DraftType:          updated.DraftType,
		SortOrder:          updated.SortOrder,
		Text:               updated.Text,
		Angle:              updated.Angle,
		Hook:               updated.Hook,
		Rationale:          updated.Rationale,
		ReferenceNotes:     updated.ReferenceNotes,
		Sources:            updated.Sources,
		Status:             updated.Status,
		PublishedMediaID:   updated.PublishedMediaID,
		PublishedPermalink: updated.PublishedPermalink,
		PublishedAt:        updated.PublishedAt,
		CreateAt:           updated.CreateAt,
	}
	return &data, nil
}
