package postgres

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

	"switchboard-core/models"
)

// ── ConnectionStore (v0.38.1) ────────────────────────

type ConnectionStore struct{}

func NewConnectionStore() *ConnectionStore { return &ConnectionStore{} }

const connCols = `id, type, package_id, scope, owner_id, name, config, is_active, created_at, updated_at`

func (s *ConnectionStore) Create(ctx context.Context, conn *models.ExtConnection) error {
	return DB.QueryRowContext(ctx, `
		INSERT INTO ext_connections (type, package_id, scope, owner_id, name, config, is_active)
		VALUES ($1, $2, $3, $4, $5, $6, $7)
		RETURNING id, created_at, updated_at`,
		conn.Type, conn.PackageID, conn.Scope, conn.OwnerID,
		conn.Name, ToJSON(conn.Config), conn.IsActive,
	).Scan(&conn.ID, &conn.CreatedAt, &conn.UpdatedAt)
}

func (s *ConnectionStore) GetByID(ctx context.Context, id string) (*models.ExtConnection, error) {
	row := DB.QueryRowContext(ctx,
		fmt.Sprintf("SELECT %s FROM ext_connections WHERE id = $1", connCols), id)
	return scanConnection(row)
}

func (s *ConnectionStore) Update(ctx context.Context, id string, patch models.ExtConnectionPatch) error {
	b := NewUpdate("ext_connections")
	if patch.Name != nil {
		b.Set("name", *patch.Name)
	}
	if patch.Config != nil {
		b.SetJSON("config", patch.Config)
	}
	if patch.IsActive != nil {
		b.Set("is_active", *patch.IsActive)
	}
	if !b.HasSets() {
		return nil
	}
	b.Where("id", id)
	_, err := b.Exec(DB)
	return err
}

func (s *ConnectionStore) Delete(ctx context.Context, id string) error {
	_, err := DB.ExecContext(ctx, "DELETE FROM ext_connections WHERE id = $1", id)
	return err
}

// ── Scoped Queries ─────────────────────────────────

func (s *ConnectionStore) ListGlobal(ctx context.Context) ([]models.ExtConnection, error) {
	return s.listByScope(ctx, models.ScopeGlobal, "")
}

func (s *ConnectionStore) ListForTeam(ctx context.Context, teamID string) ([]models.ExtConnection, error) {
	return s.listByScope(ctx, models.ScopeTeam, teamID)
}

func (s *ConnectionStore) ListForUser(ctx context.Context, userID string) ([]models.ExtConnection, error) {
	return s.listByScope(ctx, models.ScopePersonal, userID)
}

// ── Resolution ─────────────────────────────────────

// Resolve returns the first active connection matching type (and optional name)
// via the scope chain: personal → team → global.
func (s *ConnectionStore) Resolve(ctx context.Context, userID, connType, name string) (*models.ExtConnection, error) {
	q := fmt.Sprintf(`
		SELECT %s FROM ext_connections
		WHERE type = $1 AND is_active = true
		  AND (
			(scope = 'personal' AND owner_id = $2)
			OR (scope = 'team' AND owner_id IN (
				SELECT team_id FROM team_members WHERE user_id = $2
			))
			OR (scope = 'global')
		  )`, connCols)
	args := []any{connType, userID}
	if name != "" {
		q += " AND name = $3"
		args = append(args, name)
	}
	// Priority: personal(0) → team(1) → global(2).
	q += " ORDER BY CASE scope WHEN 'personal' THEN 0 WHEN 'team' THEN 1 ELSE 2 END, created_at ASC LIMIT 1"
	row := DB.QueryRowContext(ctx, q, args...)
	return scanConnection(row)
}

// ResolveAll returns all active connections of the given type accessible to the user.
func (s *ConnectionStore) ResolveAll(ctx context.Context, userID, connType string) ([]models.ExtConnection, error) {
	rows, err := DB.QueryContext(ctx, fmt.Sprintf(`
		SELECT %s FROM ext_connections
		WHERE type = $1 AND is_active = true
		  AND (
			(scope = 'personal' AND owner_id = $2)
			OR (scope = 'team' AND owner_id IN (
				SELECT team_id FROM team_members WHERE user_id = $2
			))
			OR (scope = 'global')
		  )
		ORDER BY scope ASC, name ASC`, connCols), connType, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	return scanConnections(rows)
}

// ListAccessible returns all connections accessible to the user across all types.
func (s *ConnectionStore) ListAccessible(ctx context.Context, userID string) ([]models.ExtConnection, error) {
	rows, err := DB.QueryContext(ctx, fmt.Sprintf(`
		SELECT %s FROM ext_connections
		WHERE is_active = true
		  AND (
			(scope = 'personal' AND owner_id = $1)
			OR (scope = 'team' AND owner_id IN (
				SELECT team_id FROM team_members WHERE user_id = $1
			))
			OR (scope = 'global')
		  )
		ORDER BY type ASC, scope ASC, name ASC`, connCols), userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	return scanConnections(rows)
}

// DeleteByIDAndScope deletes a connection only if it matches the scope/owner.
func (s *ConnectionStore) DeleteByIDAndScope(ctx context.Context, id, scope, ownerID string) (int64, error) {
	res, err := DB.ExecContext(ctx,
		`DELETE FROM ext_connections WHERE id = $1 AND scope = $2 AND owner_id = $3`,
		id, scope, ownerID)
	if err != nil {
		return 0, err
	}
	return res.RowsAffected()
}

// ── Internal ───────────────────────────────────────

func (s *ConnectionStore) listByScope(ctx context.Context, scope, ownerID string) ([]models.ExtConnection, error) {
	var rows *sql.Rows
	var err error
	if scope == models.ScopeGlobal {
		rows, err = DB.QueryContext(ctx,
			fmt.Sprintf("SELECT %s FROM ext_connections WHERE scope = $1 ORDER BY type, name", connCols),
			scope)
	} else {
		rows, err = DB.QueryContext(ctx,
			fmt.Sprintf("SELECT %s FROM ext_connections WHERE scope = $1 AND owner_id = $2 ORDER BY type, name", connCols),
			scope, ownerID)
	}
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	return scanConnections(rows)
}

func scanConnection(row *sql.Row) (*models.ExtConnection, error) {
	var c models.ExtConnection
	var configJSON []byte
	err := row.Scan(
		&c.ID, &c.Type, &c.PackageID, &c.Scope, &c.OwnerID,
		&c.Name, &configJSON, &c.IsActive, &c.CreatedAt, &c.UpdatedAt,
	)
	if err != nil {
		return nil, err
	}
	json.Unmarshal(configJSON, &c.Config)
	return &c, nil
}

func scanConnections(rows *sql.Rows) ([]models.ExtConnection, error) {
	var result []models.ExtConnection
	for rows.Next() {
		var c models.ExtConnection
		var configJSON []byte
		err := rows.Scan(
			&c.ID, &c.Type, &c.PackageID, &c.Scope, &c.OwnerID,
			&c.Name, &configJSON, &c.IsActive, &c.CreatedAt, &c.UpdatedAt,
		)
		if err != nil {
			return nil, err
		}
		json.Unmarshal(configJSON, &c.Config)
		result = append(result, c)
	}
	return result, rows.Err()
}
