package postgres

import (
	"context"

	"chat-switchboard/models"
)

type FolderStore struct{}

func NewFolderStore() *FolderStore { return &FolderStore{} }

func (s *FolderStore) List(ctx context.Context, userID string) ([]models.Folder, error) {
	rows, err := DB.QueryContext(ctx, `
		SELECT id, name, parent_id, sort_order, created_at, updated_at
		FROM folders WHERE user_id = $1
		ORDER BY sort_order, name
	`, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var result []models.Folder
	for rows.Next() {
		var f models.Folder
		if err := rows.Scan(&f.ID, &f.Name, &f.ParentID, &f.SortOrder,
			&f.CreatedAt, &f.UpdatedAt); err != nil {
			continue
		}
		f.UserID = userID
		result = append(result, f)
	}
	if result == nil {
		result = []models.Folder{}
	}
	return result, rows.Err()
}

func (s *FolderStore) Create(ctx context.Context, f *models.Folder) error {
	return DB.QueryRowContext(ctx, `
		INSERT INTO folders (user_id, name, parent_id, sort_order)
		VALUES ($1, $2, $3, $4)
		RETURNING id, name, parent_id, sort_order, created_at, updated_at
	`, f.UserID, f.Name, f.ParentID, f.SortOrder).Scan(
		&f.ID, &f.Name, &f.ParentID, &f.SortOrder, &f.CreatedAt, &f.UpdatedAt)
}

func (s *FolderStore) Update(ctx context.Context, folderID, userID string, name string, sortOrder *int, parentID **string) (int64, error) {
	if parentID != nil {
		res, err := DB.ExecContext(ctx, `
			UPDATE folders
			SET name       = COALESCE(NULLIF($3, ''), name),
			    sort_order = COALESCE($4, sort_order),
			    parent_id  = $5
			WHERE id = $1 AND user_id = $2
		`, folderID, userID, name, sortOrder, *parentID)
		if err != nil {
			return 0, err
		}
		return res.RowsAffected()
	}
	res, err := DB.ExecContext(ctx, `
		UPDATE folders
		SET name       = COALESCE(NULLIF($3, ''), name),
		    sort_order = COALESCE($4, sort_order)
		WHERE id = $1 AND user_id = $2
	`, folderID, userID, name, sortOrder)
	if err != nil {
		return 0, err
	}
	return res.RowsAffected()
}

func (s *FolderStore) Delete(ctx context.Context, folderID, userID string) (int64, error) {
	res, err := DB.ExecContext(ctx,
		`DELETE FROM folders WHERE id = $1 AND user_id = $2`, folderID, userID)
	if err != nil {
		return 0, err
	}
	return res.RowsAffected()
}

func (s *FolderStore) UnassignChannels(ctx context.Context, folderID, userID string) error {
	_, err := DB.ExecContext(ctx,
		`UPDATE channels SET folder_id = NULL WHERE folder_id = $1 AND user_id = $2`, folderID, userID)
	return err
}
