package sqlite

import (
	"context"
	"database/sql"

	"switchboard-core/models"
	"switchboard-core/store"
)

type NotificationPreferenceStore struct{}

func NewNotificationPreferenceStore() *NotificationPreferenceStore {
	return &NotificationPreferenceStore{}
}

func (s *NotificationPreferenceStore) Get(ctx context.Context, userID, notifType string) (*models.NotificationPreference, error) {
	var p models.NotificationPreference
	err := DB.QueryRowContext(ctx, `
		SELECT id, user_id, type, in_app, email
		FROM notification_preferences
		WHERE user_id = ? AND type = ?`, userID, notifType).Scan(
		&p.ID, &p.UserID, &p.Type, &p.InApp, &p.Email)
	if err == sql.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &p, nil
}

func (s *NotificationPreferenceStore) ListForUser(ctx context.Context, userID string) ([]models.NotificationPreference, error) {
	rows, err := DB.QueryContext(ctx, `
		SELECT id, user_id, type, in_app, email
		FROM notification_preferences
		WHERE user_id = ?
		ORDER BY type`, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var result []models.NotificationPreference
	for rows.Next() {
		var p models.NotificationPreference
		if err := rows.Scan(&p.ID, &p.UserID, &p.Type, &p.InApp, &p.Email); err != nil {
			return nil, err
		}
		result = append(result, p)
	}
	return result, rows.Err()
}

func (s *NotificationPreferenceStore) Upsert(ctx context.Context, pref *models.NotificationPreference) error {
	_, err := DB.ExecContext(ctx, `
		INSERT INTO notification_preferences (id, user_id, type, in_app, email)
		VALUES (?, ?, ?, ?, ?)
		ON CONFLICT (user_id, type) DO UPDATE SET
			in_app = excluded.in_app, email = excluded.email`,
		store.NewID(), pref.UserID, pref.Type, pref.InApp, pref.Email)
	return err
}

func (s *NotificationPreferenceStore) Delete(ctx context.Context, userID, notifType string) error {
	_, err := DB.ExecContext(ctx, `
		DELETE FROM notification_preferences
		WHERE user_id = ? AND type = ?`, userID, notifType)
	return err
}
