package rest

import (
	"context"
	"log/slog"
	"net/http"
)

// RegisterServiceHooks installs transport renderers for domain events that
// complete after the originating HTTP request has returned.
func (d *Deps) RegisterServiceHooks() {
	if d == nil || d.Svc == nil {
		return
	}
	d.Svc.SetPullRequestMergedHook(func(ctx context.Context, pullRequestIDs []uint) {
		for _, pullRequestID := range pullRequestIDs {
			pr, err := d.Svc.GetPRByID(ctx, pullRequestID)
			if err != nil {
				slog.WarnContext(ctx, "load asynchronously merged pull request for webhook", "pull_request_id", pullRequestID, "error", err)
				continue
			}
			r, err := http.NewRequestWithContext(ctx, http.MethodGet, "/", nil)
			if err != nil {
				slog.WarnContext(ctx, "build asynchronously merged pull request webhook request", "pull_request_id", pullRequestID, "error", err)
				continue
			}
			payload := d.webhookPRPayload(ctx, pr, "closed", d.prWithExtras(r, pr))
			if err := d.Svc.DispatchWebhookEvent(ctx, pr.RepositoryID, "pull_request", "closed", payload); err != nil {
				slog.WarnContext(ctx, "dispatch asynchronously merged pull request webhook", "pull_request_id", pullRequestID, "error", err)
			}
		}
	})
	d.Svc.SetPullRequestQueueEventHook(func(ctx context.Context, pullRequestIDs []uint, action string) {
		for _, pullRequestID := range pullRequestIDs {
			pr, err := d.Svc.GetPRByID(ctx, pullRequestID)
			if err != nil {
				slog.WarnContext(ctx, "load merge queue pull request for webhook", "pull_request_id", pullRequestID, "action", action, "error", err)
				continue
			}
			r, err := http.NewRequestWithContext(ctx, http.MethodGet, "/", nil)
			if err != nil {
				slog.WarnContext(ctx, "build merge queue pull request webhook request", "pull_request_id", pullRequestID, "action", action, "error", err)
				continue
			}
			payload := d.webhookPRPayload(ctx, pr, action, d.prWithExtras(r, pr))
			if err := d.Svc.DispatchWebhookEvent(ctx, pr.RepositoryID, "pull_request", action, payload); err != nil {
				slog.WarnContext(ctx, "dispatch merge queue pull request webhook", "pull_request_id", pullRequestID, "action", action, "error", err)
			}
		}
	})
}
