package handlers

import (
	"database/sql"
	"encoding/json"

	"github.com/lib/pq"
)

// pgScanStringArray returns a sql.Scanner that scans a Postgres text[] array
// into a Go string slice. Used by handler-level Postgres-specific queries.
func pgScanStringArray(dest *[]string) interface{ Scan(src interface{}) error } {
	return &pgStringArrayScanner{dest: dest}
}

type pgStringArrayScanner struct {
	dest *[]string
}

func (s *pgStringArrayScanner) Scan(src interface{}) error {
	var arr pq.StringArray
	if err := arr.Scan(src); err != nil {
		// Fallback: try JSON array (for SQLite compatibility if accidentally called)
		if b, ok := src.([]byte); ok {
			return json.Unmarshal(b, s.dest)
		}
		if str, ok := src.(string); ok {
			return json.Unmarshal([]byte(str), s.dest)
		}
		return err
	}
	*s.dest = []string(arr)
	return nil
}

// Ensure pq is importable even if not directly referenced elsewhere.
var _ sql.Scanner = &pgStringArrayScanner{}
