package handlers

import (
	"errors"
	"net/http"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgtype"

	"wherewoof/frontend/internal/auth"
)

type publicData struct {
	ID          int64
	TagCode     string
	Status      string
	ItemType    pgtype.Text
	Description pgtype.Text
	PhotoUrl    pgtype.Text
	Phone       pgtype.Text
	Address     pgtype.Text
	Notes       pgtype.Text
	IsOwner     bool
}

func (a *App) Home(w http.ResponseWriter, r *http.Request) {
	a.render(w, r, "index", "Home", nil, "")
}

// PublicTag renders the unauthenticated tag page: setup prompt, return details,
// or unavailable (suspended / not found).
func (a *App) PublicTag(w http.ResponseWriter, r *http.Request) {
	code := r.PathValue("tag_code")
	tag, err := a.Queries.GetTagByCode(r.Context(), code)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			a.render(w, r, "notfound", "Tag not found", nil, "")
			return
		}
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}

	pd := publicData{
		ID:          tag.ID,
		TagCode:     tag.TagCode,
		Status:      tag.Status,
		ItemType:    tag.ItemType,
		Description: tag.Description,
		PhotoUrl:    tag.PhotoUrl,
		Phone:       tag.Phone,
		Address:     tag.Address,
		Notes:       tag.Notes,
	}
	if uid, ok := auth.GetUserID(r); ok && tag.OwnerID.Valid && tag.OwnerID.Int64 == uid {
		pd.IsOwner = true
	}
	a.render(w, r, "public", "Found item", pd, "")
}
