package handlers

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"xorm.io/xorm"

	"github.com/forgeo/forgebucket/internal/models"
)

type PipelineHandler struct {
	db *xorm.Engine
}

func NewPipelineHandler(db *xorm.Engine) *PipelineHandler {
	return &PipelineHandler{db: db}
}

func (h *PipelineHandler) List(w http.ResponseWriter, r *http.Request) {
	ownerName := chi.URLParam(r, "owner")
	repoName := chi.URLParam(r, "repo")

	repoID, ok := h.repoID(w, ownerName, repoName)
	if !ok {
		return
	}
	_ = repoID
	// Pipeline records will be added in Phase 3 (CI integration).
	// Return empty list so the client doesn't break.
	jsonOK(w, []any{})
}

func (h *PipelineHandler) Get(w http.ResponseWriter, r *http.Request) {
	jsonError(w, "not implemented", http.StatusNotImplemented)
}

func (h *PipelineHandler) repoID(w http.ResponseWriter, ownerName, repoName string) (int64, bool) {
	var owner models.User
	found, err := h.db.Where("username = ?", ownerName).Get(&owner)
	if err != nil || !found {
		jsonError(w, "repository not found", http.StatusNotFound)
		return 0, false
	}

	var repo models.Repository
	found, err = h.db.Where("owner_id = ? AND name = ?", owner.ID, repoName).Get(&repo)
	if err != nil || !found {
		jsonError(w, "repository not found", http.StatusNotFound)
		return 0, false
	}
	return repo.ID, true
}
