package workshop

import (
	"context"
	"crypto/rand"
	"encoding/base32"
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"github.com/google/uuid"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// Store handles workshop session data persistence
type Store struct {
	pool *pgxpool.Pool
}

// NewStore creates a new workshop store
func NewStore(pool *pgxpool.Pool) *Store {
	return &Store{pool: pool}
}

// ============================================================================
// Session CRUD Operations
// ============================================================================

// CreateSession creates a new workshop session
func (s *Store) CreateSession(ctx context.Context, session *Session) error {
	session.ID = uuid.New()
	session.CreatedAt = time.Now().UTC()
	session.UpdatedAt = session.CreatedAt
	if session.Status == "" {
		session.Status = SessionStatusDraft
	}
	if session.JoinCode == "" {
		session.JoinCode = generateJoinCode()
	}

	settings, _ := json.Marshal(session.Settings)

	_, err := s.pool.Exec(ctx, `
		INSERT INTO workshop_sessions (
			id, tenant_id, namespace_id,
			title, description, session_type, status,
			wizard_schema, current_step, total_steps,
			assessment_id, roadmap_id, portfolio_id,
			scheduled_start, scheduled_end, actual_start, actual_end,
			join_code, require_auth, allow_anonymous,
			settings,
			created_at, updated_at, created_by
		) VALUES (
			$1, $2, $3,
			$4, $5, $6, $7,
			$8, $9, $10,
			$11, $12, $13,
			$14, $15, $16, $17,
			$18, $19, $20,
			$21,
			$22, $23, $24
		)
	`,
		session.ID, session.TenantID, session.NamespaceID,
		session.Title, session.Description, session.SessionType, string(session.Status),
		session.WizardSchema, session.CurrentStep, session.TotalSteps,
		session.AssessmentID, session.RoadmapID, session.PortfolioID,
		session.ScheduledStart, session.ScheduledEnd, session.ActualStart, session.ActualEnd,
		session.JoinCode, session.RequireAuth, session.AllowAnonymous,
		settings,
		session.CreatedAt, session.UpdatedAt, session.CreatedBy,
	)

	return err
}

// GetSession retrieves a session by ID
func (s *Store) GetSession(ctx context.Context, id uuid.UUID) (*Session, error) {
	var session Session
	var status string
	var settings []byte

	err := s.pool.QueryRow(ctx, `
		SELECT
			id, tenant_id, namespace_id,
			title, description, session_type, status,
			wizard_schema, current_step, total_steps,
			assessment_id, roadmap_id, portfolio_id,
			scheduled_start, scheduled_end, actual_start, actual_end,
			join_code, require_auth, allow_anonymous,
			settings,
			created_at, updated_at, created_by
		FROM workshop_sessions WHERE id = $1
	`, id).Scan(
		&session.ID, &session.TenantID, &session.NamespaceID,
		&session.Title, &session.Description, &session.SessionType, &status,
		&session.WizardSchema, &session.CurrentStep, &session.TotalSteps,
		&session.AssessmentID, &session.RoadmapID, &session.PortfolioID,
		&session.ScheduledStart, &session.ScheduledEnd, &session.ActualStart, &session.ActualEnd,
		&session.JoinCode, &session.RequireAuth, &session.AllowAnonymous,
		&settings,
		&session.CreatedAt, &session.UpdatedAt, &session.CreatedBy,
	)

	if err == pgx.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	session.Status = SessionStatus(status)
	json.Unmarshal(settings, &session.Settings)

	return &session, nil
}

// GetSessionByJoinCode retrieves a session by its join code
func (s *Store) GetSessionByJoinCode(ctx context.Context, code string) (*Session, error) {
	var id uuid.UUID
	err := s.pool.QueryRow(ctx,
		"SELECT id FROM workshop_sessions WHERE join_code = $1",
		strings.ToUpper(code),
	).Scan(&id)

	if err == pgx.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	return s.GetSession(ctx, id)
}

// ListSessions lists sessions for a tenant with optional filters
func (s *Store) ListSessions(ctx context.Context, tenantID uuid.UUID, filters *SessionFilters) ([]Session, error) {
	query := `
		SELECT
			id, tenant_id, namespace_id,
			title, description, session_type, status,
			wizard_schema, current_step, total_steps,
			assessment_id, roadmap_id, portfolio_id,
			scheduled_start, scheduled_end, actual_start, actual_end,
			join_code, require_auth, allow_anonymous,
			settings,
			created_at, updated_at, created_by
		FROM workshop_sessions WHERE tenant_id = $1`

	args := []interface{}{tenantID}
	argIdx := 2

	if filters != nil {
		if filters.Status != "" {
			query += fmt.Sprintf(" AND status = $%d", argIdx)
			args = append(args, string(filters.Status))
			argIdx++
		}
		if filters.SessionType != "" {
			query += fmt.Sprintf(" AND session_type = $%d", argIdx)
			args = append(args, filters.SessionType)
			argIdx++
		}
		if filters.AssessmentID != nil {
			query += fmt.Sprintf(" AND assessment_id = $%d", argIdx)
			args = append(args, *filters.AssessmentID)
			argIdx++
		}
		if filters.CreatedBy != nil {
			query += fmt.Sprintf(" AND created_by = $%d", argIdx)
			args = append(args, *filters.CreatedBy)
			argIdx++
		}
	}

	query += " ORDER BY created_at DESC"

	if filters != nil && filters.Limit > 0 {
		query += fmt.Sprintf(" LIMIT $%d", argIdx)
		args = append(args, filters.Limit)
		argIdx++

		if filters.Offset > 0 {
			query += fmt.Sprintf(" OFFSET $%d", argIdx)
			args = append(args, filters.Offset)
		}
	}

	rows, err := s.pool.Query(ctx, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var sessions []Session
	for rows.Next() {
		var session Session
		var status string
		var settings []byte

		err := rows.Scan(
			&session.ID, &session.TenantID, &session.NamespaceID,
			&session.Title, &session.Description, &session.SessionType, &status,
			&session.WizardSchema, &session.CurrentStep, &session.TotalSteps,
			&session.AssessmentID, &session.RoadmapID, &session.PortfolioID,
			&session.ScheduledStart, &session.ScheduledEnd, &session.ActualStart, &session.ActualEnd,
			&session.JoinCode, &session.RequireAuth, &session.AllowAnonymous,
			&settings,
			&session.CreatedAt, &session.UpdatedAt, &session.CreatedBy,
		)
		if err != nil {
			return nil, err
		}

		session.Status = SessionStatus(status)
		json.Unmarshal(settings, &session.Settings)

		sessions = append(sessions, session)
	}

	return sessions, nil
}

// UpdateSession updates a session
func (s *Store) UpdateSession(ctx context.Context, session *Session) error {
	session.UpdatedAt = time.Now().UTC()

	settings, _ := json.Marshal(session.Settings)

	_, err := s.pool.Exec(ctx, `
		UPDATE workshop_sessions SET
			title = $2, description = $3, status = $4,
			wizard_schema = $5, current_step = $6, total_steps = $7,
			scheduled_start = $8, scheduled_end = $9,
			actual_start = $10, actual_end = $11,
			require_auth = $12, allow_anonymous = $13,
			settings = $14,
			updated_at = $15
		WHERE id = $1
	`,
		session.ID, session.Title, session.Description, string(session.Status),
		session.WizardSchema, session.CurrentStep, session.TotalSteps,
		session.ScheduledStart, session.ScheduledEnd,
		session.ActualStart, session.ActualEnd,
		session.RequireAuth, session.AllowAnonymous,
		settings,
		session.UpdatedAt,
	)

	return err
}

// UpdateSessionStatus updates only the session status
func (s *Store) UpdateSessionStatus(ctx context.Context, id uuid.UUID, status SessionStatus) error {
	now := time.Now().UTC()

	query := "UPDATE workshop_sessions SET status = $2, updated_at = $3"

	if status == SessionStatusActive {
		query += ", actual_start = COALESCE(actual_start, $3)"
	} else if status == SessionStatusCompleted || status == SessionStatusCancelled {
		query += ", actual_end = $3"
	}

	query += " WHERE id = $1"

	_, err := s.pool.Exec(ctx, query, id, string(status), now)
	return err
}

// AdvanceStep advances the session to the next step
func (s *Store) AdvanceStep(ctx context.Context, id uuid.UUID) error {
	_, err := s.pool.Exec(ctx, `
		UPDATE workshop_sessions SET
			current_step = current_step + 1,
			updated_at = NOW()
		WHERE id = $1 AND current_step < total_steps
	`, id)
	return err
}

// DeleteSession deletes a session and its related data
func (s *Store) DeleteSession(ctx context.Context, id uuid.UUID) error {
	// Delete in order: comments, responses, step_progress, participants, session
	_, err := s.pool.Exec(ctx, "DELETE FROM workshop_comments WHERE session_id = $1", id)
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, "DELETE FROM workshop_responses WHERE session_id = $1", id)
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, "DELETE FROM workshop_step_progress WHERE session_id = $1", id)
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, "DELETE FROM workshop_participants WHERE session_id = $1", id)
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, "DELETE FROM workshop_sessions WHERE id = $1", id)
	return err
}

// ============================================================================
// Helpers
// ============================================================================

// generateJoinCode generates a random 6-character join code
func generateJoinCode() string {
	b := make([]byte, 4)
	rand.Read(b)
	code := base32.StdEncoding.EncodeToString(b)[:6]
	return strings.ToUpper(code)
}
