package sqlite

import (
	"context"

	"chat-switchboard/models"
	"chat-switchboard/store"
)

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 = ?
		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,
			st(&f.CreatedAt), st(&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 {
	f.ID = store.NewID()
	_, err := DB.ExecContext(ctx, `
		INSERT INTO folders (id, user_id, name, parent_id, sort_order)
		VALUES (?, ?, ?, ?, ?)
	`, f.ID, f.UserID, f.Name, f.ParentID, f.SortOrder)
	if err != nil {
		return err
	}
	return DB.QueryRowContext(ctx, `
		SELECT name, parent_id, sort_order, created_at, updated_at
		FROM folders WHERE id = ?
	`, f.ID).Scan(&f.Name, &f.ParentID, &f.SortOrder, st(&f.CreatedAt), st(&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(?, ''), name),
			    sort_order = COALESCE(?, sort_order),
			    parent_id  = ?
			WHERE id = ? AND user_id = ?
		`, name, sortOrder, *parentID, folderID, userID)
		if err != nil {
			return 0, err
		}
		return res.RowsAffected()
	}
	res, err := DB.ExecContext(ctx, `
		UPDATE folders
		SET name       = COALESCE(NULLIF(?, ''), name),
		    sort_order = COALESCE(?, sort_order)
		WHERE id = ? AND user_id = ?
	`, name, sortOrder, folderID, userID)
	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 = ? AND user_id = ?`, 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 = ? AND user_id = ?`, folderID, userID)
	return err
}
