package store

import (
	"time"

	"github.com/google/uuid"
)

// CreateNotificationForTaskAssignment creates a notification when a task is assigned
func (s *PostgresStore) CreateNotificationForTaskAssignment(workspaceSlug, assigneeEmail, taskTitle, taskID string) {
	s.CreateNotification(CreateNotificationInput{
		WorkspaceSlug: workspaceSlug,
		UserEmail:     assigneeEmail,
		Type:          "task_assigned",
		Title:         "Task assigned to you",
		Body:          "You have been assigned to: " + taskTitle,
		EntityType:    strPtr("task"),
		EntityID:      strPtr(taskID),
	})
}

// CreateNotificationForMention creates a notification when a user is mentioned
func (s *PostgresStore) CreateNotificationForMention(workspaceSlug, mentionedEmail, mentionerName, entityType, entityID, context string) {
	s.CreateNotification(CreateNotificationInput{
		WorkspaceSlug: workspaceSlug,
		UserEmail:     mentionedEmail,
		Type:          "mention",
		Title:         mentionerName + " mentioned you",
		Body:          context,
		EntityType:    strPtr(entityType),
		EntityID:      strPtr(entityID),
	})
}

// CreateNotificationForComment creates a notification for a new comment on an entity
func (s *PostgresStore) CreateNotificationForComment(workspaceSlug, ownerEmail, commenterName, entityType, entityID, entityTitle string) {
	s.CreateNotification(CreateNotificationInput{
		WorkspaceSlug: workspaceSlug,
		UserEmail:     ownerEmail,
		Type:          "comment",
		Title:         commenterName + " commented on " + entityTitle,
		Body:          "New comment on " + entityType,
		EntityType:    strPtr(entityType),
		EntityID:      strPtr(entityID),
	})
}

// CreateNotificationForTaskCompletion creates a notification when a task is completed
func (s *PostgresStore) CreateNotificationForTaskCompletion(workspaceSlug, assignerEmail, taskTitle, taskID string) {
	s.CreateNotification(CreateNotificationInput{
		WorkspaceSlug: workspaceSlug,
		UserEmail:     assignerEmail,
		Type:          "task_completed",
		Title:         "Task completed: " + taskTitle,
		Body:          "A task you assigned has been completed",
		EntityType:    strPtr("task"),
		EntityID:      strPtr(taskID),
	})
}

// CreateNotificationForEventReminder creates a notification for an upcoming event
func (s *PostgresStore) CreateNotificationForEventReminder(workspaceSlug, userEmail, eventTitle, eventID string) {
	s.CreateNotification(CreateNotificationInput{
		WorkspaceSlug: workspaceSlug,
		UserEmail:     userEmail,
		Type:          "event_reminder",
		Title:         "Upcoming event: " + eventTitle,
		Body:          "Your event is starting soon",
		EntityType:    strPtr("event"),
		EntityID:      strPtr(eventID),
	})
}

// TriggerWebhooks triggers all webhooks for a given event type
func (s *PostgresStore) TriggerWebhooks(workspaceSlug, eventType string, payload map[string]interface{}) {
	// Get all active webhooks for this workspace
	rows, err := s.db.Query(`
		SELECT id, url, secret, events
		FROM webhooks
		WHERE workspace_slug = $1 AND active = true
	`, workspaceSlug)
	if err != nil {
		return
	}
	defer rows.Close()

	for rows.Next() {
		var id, url, secret, eventsJSON string
		if err := rows.Scan(&id, &url, &secret, &eventsJSON); err != nil {
			continue
		}

		// Check if this webhook subscribes to the event
		// Simple string contains check for the event type in the JSON array
		if !containsEvent(eventsJSON, eventType) {
			continue
		}

		// Update last triggered timestamp
		s.db.Exec(`UPDATE webhooks SET last_triggered_at = $1 WHERE id = $2`, time.Now().UTC(), id)

		// Webhook delivery would happen here in a goroutine
		// For now, we just mark it as triggered
		go deliverWebhook(url, secret, eventType, payload)
	}
}

func strPtr(s string) *string {
	return &s
}

func containsEvent(eventsJSON, eventType string) bool {
	// Simple check - in production would parse JSON properly
	return len(eventsJSON) > 2 && 
		(eventsJSON == "[]" || 
		 eventsJSON == "[\""+eventType+"\"]" ||
		 containsSubstring(eventsJSON, "\""+eventType+"\""))
}

func containsSubstring(s, substr string) bool {
	for i := 0; i <= len(s)-len(substr); i++ {
		if s[i:i+len(substr)] == substr {
			return true
		}
	}
	return false
}

func deliverWebhook(url, secret, eventType string, payload map[string]interface{}) {
	// Webhook delivery implementation
	// In production, this would make an HTTP POST request
	// with proper signature using the secret
}