package external

import (
	"fmt"
	"sync"
)

// ExternalTask represents an imported task from external systems
type ExternalTask struct {
	ID         string
	Source     string   // "github", "linear", "jira"
	ExternalID string
	Title      string
	Status     string
	Body       string
	Labels     []string
	Assignee   string
}

// TaskImporter imports tasks from external systems
type TaskImporter struct {
	mu    sync.RWMutex
	tasks map[string]*ExternalTask
}

// NewTaskImporter creates a new task importer
func NewTaskImporter() *TaskImporter {
	return &TaskImporter{
		tasks: make(map[string]*ExternalTask),
	}
}

// Import imports a task from external source
func (ti *TaskImporter) Import(task *ExternalTask) error {
	if task.ID == "" {
		return fmt.Errorf("task ID required")
	}

	ti.mu.Lock()
	defer ti.mu.Unlock()

	ti.tasks[task.ID] = task
	return nil
}

// GetTask retrieves an imported task
func (ti *TaskImporter) GetTask(id string) (*ExternalTask, bool) {
	ti.mu.RLock()
	defer ti.mu.RUnlock()

	task, exists := ti.tasks[id]
	return task, exists
}

// ListTasks lists all imported tasks
func (ti *TaskImporter) ListTasks() map[string]*ExternalTask {
	ti.mu.RLock()
	defer ti.mu.RUnlock()

	result := make(map[string]*ExternalTask)
	for id, task := range ti.tasks {
		result[id] = task
	}

	return result
}

// UpdateStatus updates task status
func (ti *TaskImporter) UpdateStatus(id string, status string) error {
	ti.mu.Lock()
	defer ti.mu.Unlock()

	task, exists := ti.tasks[id]
	if !exists {
		return fmt.Errorf("task not found: %s", id)
	}

	task.Status = status
	return nil
}

// GetBySource lists tasks from a specific source
func (ti *TaskImporter) GetBySource(source string) []*ExternalTask {
	ti.mu.RLock()
	defer ti.mu.RUnlock()

	result := make([]*ExternalTask, 0)
	for _, task := range ti.tasks {
		if task.Source == source {
			result = append(result, task)
		}
	}

	return result
}

// Remove removes a task
func (ti *TaskImporter) Remove(id string) error {
	ti.mu.Lock()
	defer ti.mu.Unlock()

	if _, exists := ti.tasks[id]; !exists {
		return fmt.Errorf("task not found: %s", id)
	}

	delete(ti.tasks, id)
	return nil
}
