package store

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

	"github.com/google/uuid"

	thoughttypes "git.warky.dev/wdevs/amcs/internal/types"
)

func (db *DB) InsertLink(ctx context.Context, link thoughttypes.ThoughtLink) error {
	_, err := db.pool.Exec(ctx, `
		insert into thought_links (from_id, to_id, relation)
		select f.id, t.id, $3
		from thoughts f, thoughts t
		where f.guid = $1 and t.guid = $2
	`, link.FromID, link.ToID, link.Relation)
	if err != nil {
		return fmt.Errorf("insert link: %w", err)
	}
	return nil
}

func (db *DB) LinkedThoughts(ctx context.Context, thoughtID uuid.UUID) ([]thoughttypes.LinkedThought, error) {
	rows, err := db.pool.Query(ctx, `
		select t.guid, t.content, t.metadata, t.project_id, t.archived_at, t.created_at, t.updated_at, l.relation, 'outgoing' as direction, l.created_at
		from thought_links l
		join thoughts t on t.id = l.to_id
		where l.from_id = (select id from thoughts where guid = $1)
		union all
		select t.guid, t.content, t.metadata, t.project_id, t.archived_at, t.created_at, t.updated_at, l.relation, 'incoming' as direction, l.created_at
		from thought_links l
		join thoughts t on t.id = l.from_id
		where l.to_id = (select id from thoughts where guid = $1)
		order by created_at desc
	`, thoughtID)
	if err != nil {
		return nil, fmt.Errorf("query linked thoughts: %w", err)
	}
	defer rows.Close()

	links := make([]thoughttypes.LinkedThought, 0)
	for rows.Next() {
		var linked thoughttypes.LinkedThought
		var metadataBytes []byte
		if err := rows.Scan(
			&linked.Thought.ID,
			&linked.Thought.Content,
			&metadataBytes,
			&linked.Thought.ProjectID,
			&linked.Thought.ArchivedAt,
			&linked.Thought.CreatedAt,
			&linked.Thought.UpdatedAt,
			&linked.Relation,
			&linked.Direction,
			&linked.CreatedAt,
		); err != nil {
			return nil, fmt.Errorf("scan linked thought: %w", err)
		}
		if err := json.Unmarshal(metadataBytes, &linked.Thought.Metadata); err != nil {
			return nil, fmt.Errorf("decode linked thought metadata: %w", err)
		}
		links = append(links, linked)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("iterate linked thoughts: %w", err)
	}
	return links, nil
}
