package search

import (
	"strings"

	"senlinai-agent/backend/internal/models"
)

type Service struct {
}

type Result struct {
	Type      string `json:"type"`
	ID        uint   `json:"id"`
	ProjectID uint   `json:"project_id"`
	Title     string `json:"title"`
	Snippet   string `json:"snippet"`
}

func NewService() *Service {
	return &Service{}
}

func (s *Service) Search(userID uint, query string) ([]Result, error) {
	query = strings.TrimSpace(query)
	if query == "" {
		return []Result{}, nil
	}
	if models.DBService.Dialector.Name() == "postgres" {
		return s.searchPostgres(userID, query)
	}

	like := "%" + query + "%"
	results := []Result{}
	var projects []models.SenlinAgentProject
	if err := models.DBService.Where("owner_id = ? AND (name LIKE ? OR description LIKE ?)", userID, like, like).Find(&projects).Error; err != nil {
		return nil, err
	}
	for _, project := range projects {
		results = append(results, Result{Type: "project", ID: project.ID, ProjectID: project.ID, Title: project.Name, Snippet: project.Description})
	}

	var tasks []models.SenlinAgentTask
	if err := models.DBService.Joins("JOIN senlin_agent_projects ON senlin_agent_projects.id = senlin_agent_tasks.project_id").
		Where("senlin_agent_projects.owner_id = ? AND (senlin_agent_tasks.title LIKE ? OR senlin_agent_tasks.description LIKE ?)", userID, like, like).
		Find(&tasks).Error; err != nil {
		return nil, err
	}
	for _, task := range tasks {
		results = append(results, Result{Type: "task", ID: task.ID, ProjectID: task.ProjectID, Title: task.Title, Snippet: task.Description})
	}

	var notes []models.SenlinAgentNote
	if err := models.DBService.Joins("JOIN senlin_agent_projects ON senlin_agent_projects.id = senlin_agent_notes.project_id").
		Where("senlin_agent_projects.owner_id = ? AND (senlin_agent_notes.title LIKE ? OR senlin_agent_notes.markdown LIKE ?)", userID, like, like).
		Find(&notes).Error; err != nil {
		return nil, err
	}
	for _, note := range notes {
		results = append(results, Result{Type: "note", ID: note.ID, ProjectID: note.ProjectID, Title: note.Title, Snippet: note.Markdown})
	}

	var sources []models.SenlinAgentSource
	if err := models.DBService.Joins("JOIN senlin_agent_projects ON senlin_agent_projects.id = senlin_agent_sources.project_id").
		Where("senlin_agent_projects.owner_id = ? AND (senlin_agent_sources.title LIKE ? OR senlin_agent_sources.url LIKE ? OR senlin_agent_sources.content_text LIKE ?)", userID, like, like, like).
		Find(&sources).Error; err != nil {
		return nil, err
	}
	for _, source := range sources {
		results = append(results, Result{Type: "source", ID: source.ID, ProjectID: source.ProjectID, Title: source.Title, Snippet: source.ContentText})
	}

	var inboxItems []models.SenlinAgentInboxItem
	if err := models.DBService.Joins("JOIN senlin_agent_projects ON senlin_agent_projects.id = senlin_agent_inbox_items.project_id").
		Where("senlin_agent_projects.owner_id = ? AND (senlin_agent_inbox_items.title LIKE ? OR senlin_agent_inbox_items.body LIKE ?)", userID, like, like).
		Find(&inboxItems).Error; err != nil {
		return nil, err
	}
	for _, item := range inboxItems {
		results = append(results, Result{Type: "inbox", ID: item.ID, ProjectID: item.ProjectID, Title: item.Title, Snippet: item.Body})
	}

	var sessions []models.SenlinAgentAISession
	if err := models.DBService.Joins("JOIN senlin_agent_projects ON senlin_agent_projects.id = senlin_agent_ai_sessions.project_id").
		Where("senlin_agent_projects.owner_id = ? AND (senlin_agent_ai_sessions.title LIKE ? OR senlin_agent_ai_sessions.context LIKE ?)", userID, like, like).
		Find(&sessions).Error; err != nil {
		return nil, err
	}
	for _, session := range sessions {
		results = append(results, Result{Type: "ai_session", ID: session.ID, ProjectID: session.ProjectID, Title: session.Title, Snippet: session.Context})
	}
	return results, nil
}

func (s *Service) searchPostgres(userID uint, query string) ([]Result, error) {
	var results []Result
	err := models.DBService.Raw(`
		SELECT 'project' AS type, p.id, p.id AS project_id, p.name AS title, p.description AS snippet
		FROM senlin_agent_projects p
		WHERE p.owner_id = ?
		  AND to_tsvector('simple', coalesce(p.name, '') || ' ' || coalesce(p.description, '')) @@ plainto_tsquery('simple', ?)
		UNION ALL
		SELECT 'task' AS type, t.id, t.project_id, t.title, t.description AS snippet
		FROM senlin_agent_tasks t
		JOIN senlin_agent_projects p ON p.id = t.project_id
		WHERE p.owner_id = ?
		  AND to_tsvector('simple', coalesce(t.title, '') || ' ' || coalesce(t.description, '')) @@ plainto_tsquery('simple', ?)
		UNION ALL
		SELECT 'note' AS type, n.id, n.project_id, n.title, n.markdown AS snippet
		FROM senlin_agent_notes n
		JOIN senlin_agent_projects p ON p.id = n.project_id
		WHERE p.owner_id = ?
		  AND to_tsvector('simple', coalesce(n.title, '') || ' ' || coalesce(n.markdown, '')) @@ plainto_tsquery('simple', ?)
		UNION ALL
		SELECT 'source' AS type, s.id, s.project_id, s.title, s.content_text AS snippet
		FROM senlin_agent_sources s
		JOIN senlin_agent_projects p ON p.id = s.project_id
		WHERE p.owner_id = ?
		  AND to_tsvector('simple', coalesce(s.title, '') || ' ' || coalesce(s.url, '') || ' ' || coalesce(s.content_text, '')) @@ plainto_tsquery('simple', ?)
		UNION ALL
		SELECT 'inbox' AS type, i.id, i.project_id, i.title, i.body AS snippet
		FROM senlin_agent_inbox_items i
		JOIN senlin_agent_projects p ON p.id = i.project_id
		WHERE p.owner_id = ?
		  AND to_tsvector('simple', coalesce(i.title, '') || ' ' || coalesce(i.body, '')) @@ plainto_tsquery('simple', ?)
		UNION ALL
		SELECT 'ai_session' AS type, a.id, a.project_id, a.title, a.context AS snippet
		FROM senlin_agent_ai_sessions a
		JOIN senlin_agent_projects p ON p.id = a.project_id
		WHERE p.owner_id = ?
		  AND to_tsvector('simple', coalesce(a.title, '') || ' ' || coalesce(a.context, '')) @@ plainto_tsquery('simple', ?)
		LIMIT 50
	`, userID, query, userID, query, userID, query, userID, query, userID, query, userID, query).Scan(&results).Error
	return results, err
}
