package user

import (
	"context"
	"encoding/json"

	"hyapp/pkg/appcode"
	userdomain "hyapp/services/user-service/internal/domain/user"
)

// SubmitReport 持久化举报事实。用户目标会校验同 App 存在；房间目标只记录 room_id，不回查 room-service 明细表。
func (r *Repository) SubmitReport(ctx context.Context, report userdomain.Report) (userdomain.Report, error) {
	tx, err := r.db.BeginTx(ctx, nil)
	if err != nil {
		return userdomain.Report{}, err
	}
	defer tx.Rollback()

	appCode := appcode.FromContext(ctx)
	if err := ensureSocialUser(ctx, tx, appCode, report.ReporterUserID); err != nil {
		return userdomain.Report{}, err
	}
	if report.UserID > 0 {
		if err := ensureSocialUser(ctx, tx, appCode, report.UserID); err != nil {
			return userdomain.Report{}, err
		}
	}
	imageURLsJSON, err := json.Marshal(report.ImageURLs)
	if err != nil {
		return userdomain.Report{}, err
	}
	if _, err := tx.ExecContext(ctx, `
		INSERT INTO user_reports (
			app_code, report_id, reporter_user_id, target_type, target_user_id, room_id,
			report_type, reason, image_urls_json, status, request_id, created_at_ms, updated_at_ms
		) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		appCode, report.ReportID, report.ReporterUserID, report.TargetType, nullableReportUserID(report.UserID), report.RoomID,
		report.ReportType, report.Reason, string(imageURLsJSON), report.Status, report.RequestID, report.CreatedAtMs, report.UpdatedAtMs,
	); err != nil {
		return userdomain.Report{}, err
	}
	report.AppCode = appCode
	return report, tx.Commit()
}

func nullableReportUserID(userID int64) any {
	if userID <= 0 {
		return nil
	}
	return userID
}
