package pulls

import (
	"fmt"
	"net/http"

	"tangled.org/core/appview/db"
	"tangled.org/core/appview/models"
	"tangled.org/core/appview/reporesolver"
	"tangled.org/core/orm"

	"github.com/bluesky-social/indigo/atproto/syntax"
)

func (s *Pulls) ClosePull(w http.ResponseWriter, r *http.Request) {
	l := s.logger.With("handler", "ClosePull")
	l.Debug("request")

	user := s.oauth.GetMultiAccountUser(r)
	if user == nil {
		l.Error("nil user")
		s.pages.Notice(w, "pull-action-error", "You must be logged in to close this pull.")
		return
	}
	l = l.With("user", user.Did)

	f, err := s.repoResolver.Resolve(r)
	if err != nil {
		l.Error("failed to resolve repo", "err", err)
		return
	}

	pull, ok := r.Context().Value("pull").(*models.Pull)
	if !ok {
		l.Error("failed to get pull")
		s.pages.Notice(w, "pull-action-error", "Failed to close pull. Try again later.")
		return
	}
	l = l.With("pull", pull.AtUri(), "pull_id", pull.PullId, "state", pull.State)

	// auth filter: only owner or collaborators can close
	roles := s.acl.RolesInRepo(r.Context(), f, user.Did)
	isOwner := roles.IsOwner()
	isCollaborator := roles.IsCollaborator()
	isPullAuthor := syntax.DID(user.Did) == pull.OwnerDid
	isCloseAllowed := isOwner || isCollaborator || isPullAuthor
	if !isCloseAllowed {
		l.Error("unauthorized to close pull", "is_owner", isOwner, "is_collaborator", isCollaborator, "is_pull_author", isPullAuthor)
		s.pages.Notice(w, "pull-action-error", "You are unauthorized to close this pull.")
		return
	}

	if err := s.writePullStatusRecord(r, user.Did, pull.AtUri(), models.StateClosed); err != nil {
		l.Error("failed to write issue state record", "err", err)
		s.pages.Notice(w, "issue-action", "Failed to close issue. Try again later.")
		return
	}

	tx, err := s.db.BeginTx(r.Context(), nil)
	if err != nil {
		l.Error("failed to start transaction", "err", err)
		s.pages.Notice(w, "pull-action-error", "Failed to close pull.")
		return
	}
	defer tx.Rollback()

	err = db.ClosePulls(
		tx,
		orm.FilterEq("at_uri", pull.AtUri()),
	)
	if err != nil {
		l.Error("failed to close pulls in database", "err", err)
		s.pages.Notice(w, "pull-action-error", "Failed to close pull.")
		return
	}

	// Commit the transaction
	if err = tx.Commit(); err != nil {
		l.Error("failed to commit transaction", "err", err)
		s.pages.Notice(w, "pull-action-error", "Failed to close pull.")
		return
	}

	s.notifier.NewPullState(r.Context(), syntax.DID(user.Did), pull)

	ownerSlashRepo := reporesolver.GetBaseRepoPath(r, f)
	s.pages.HxLocation(w, fmt.Sprintf("/%s/pulls/%d", ownerSlashRepo, pull.PullId))
}

func (s *Pulls) ReopenPull(w http.ResponseWriter, r *http.Request) {
	l := s.logger.With("handler", "ReopenPull")

	user := s.oauth.GetMultiAccountUser(r)
	if user == nil {
		l.Error("nil user")
		s.pages.Notice(w, "pull-action-error", "You must be logged in to reopen this pull.")
		return
	}
	l = l.With("user", user.Did)

	f, err := s.repoResolver.Resolve(r)
	if err != nil {
		l.Error("failed to resolve repo", "err", err)
		s.pages.Notice(w, "pull-action-error", "Failed to reopen pull.")
		return
	}

	pull, ok := r.Context().Value("pull").(*models.Pull)
	if !ok {
		l.Error("failed to get pull")
		s.pages.Notice(w, "pull-action-error", "Failed to reopen pull. Try again later.")
		return
	}
	l = l.With("pull", pull.AtUri(), "pull_id", pull.PullId, "state", pull.State)

	// auth filter: only owner or collaborators can close
	roles := s.acl.RolesInRepo(r.Context(), f, user.Did)
	isOwner := roles.IsOwner()
	isCollaborator := roles.IsCollaborator()
	isPullAuthor := syntax.DID(user.Did) == pull.OwnerDid
	isCloseAllowed := isOwner || isCollaborator || isPullAuthor
	if !isCloseAllowed {
		l.Error("unauthorized to reopen pull", "is_owner", isOwner, "is_collaborator", isCollaborator, "is_pull_author", isPullAuthor)
		s.pages.Notice(w, "pull-action-error", "You are unauthorized to reopen this pull.")
		return
	}

	if err := s.writePullStatusRecord(r, user.Did, pull.AtUri(), models.StateOpen); err != nil {
		l.Error("failed to write issue state record", "err", err)
		s.pages.Notice(w, "issue-action", "Failed to close issue. Try again later.")
		return
	}

	tx, err := s.db.BeginTx(r.Context(), nil)
	if err != nil {
		l.Error("failed to start transaction", "err", err)
		s.pages.Notice(w, "pull-action-error", "Failed to reopen pull.")
		return
	}
	defer tx.Rollback()

	err = db.ReopenPulls(
		tx,
		orm.FilterEq("at_uri", pull.AtUri()),
	)
	if err != nil {
		l.Error("failed to reopen pulls in database", "err", err)
		s.pages.Notice(w, "pull-action-error", "Failed to reopen pull.")
		return
	}

	// Commit the transaction
	if err = tx.Commit(); err != nil {
		l.Error("failed to commit transaction", "err", err)
		s.pages.Notice(w, "pull-action-error", "Failed to reopen pull.")
		return
	}

	s.notifier.NewPullState(r.Context(), syntax.DID(user.Did), pull)

	ownerSlashRepo := reporesolver.GetBaseRepoPath(r, f)
	s.pages.HxLocation(w, fmt.Sprintf("/%s/pulls/%d", ownerSlashRepo, pull.PullId))
}
