package store

import (
	"context"
	"fmt"

	"github.com/google/uuid"

	"git.warky.dev/wdevs/amcs/internal/generatedmodels"
	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.id, 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.id, 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 model generatedmodels.ModelPublicThoughts
		if err := rows.Scan(
			&model.ID,
			&model.GUID,
			&model.Content,
			&model.Metadata,
			&model.ProjectID,
			&model.ArchivedAt,
			&model.CreatedAt,
			&model.UpdatedAt,
			&linked.Relation,
			&linked.Direction,
			&linked.CreatedAt,
		); err != nil {
			return nil, fmt.Errorf("scan linked thought: %w", err)
		}
		thought, err := thoughtFromModel(model)
		if err != nil {
			return nil, fmt.Errorf("map linked thought: %w", err)
		}
		linked.Thought = thought
		links = append(links, linked)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("iterate linked thoughts: %w", err)
	}
	return links, nil
}
