/**
 * Repository tests for settings module — in-memory datastore.
 */

import { describe, it, expect, beforeEach, afterAll } from 'vitest';
import { MemoryDatastoreProvider } from '@bytelyst/datastore';
import { setProvider, _resetDatastoreProvider } from '../../lib/datastore.js';
import { getSettingsId, getByUserId, upsert } from './repository.js';
import type { UserSettingsDoc } from './types.js';

const baseSettings: UserSettingsDoc = {
  id: 'set_lysnrai_user_1',
  productId: 'lysnrai',
  userId: 'user_1',
  settings: { theme: 'dark', language: 'en' },
  deviceOverrides: { dev_mac_001: { volume: 0.8 } },
  createdAt: '2026-02-16T00:00:00Z',
  updatedAt: '2026-02-16T00:00:00Z',
};

describe('settings repository', () => {
  beforeEach(() => {
    setProvider(new MemoryDatastoreProvider());
  });

  afterAll(() => {
    _resetDatastoreProvider();
  });

  describe('getSettingsId', () => {
    it('generates correct id format', () => {
      expect(getSettingsId('lysnrai', 'user_1')).toBe('set_lysnrai_user_1');
    });

    it('handles different products', () => {
      expect(getSettingsId('mindlyst', 'user_2')).toBe('set_mindlyst_user_2');
    });
  });

  describe('getByUserId', () => {
    it('returns settings when found', async () => {
      await upsert(baseSettings);
      const result = await getByUserId('user_1', 'lysnrai');
      expect(result).toEqual(baseSettings);
    });

    it('returns null when not found', async () => {
      const result = await getByUserId('user_1', 'lysnrai');
      expect(result).toBeNull();
    });
  });

  describe('upsert', () => {
    it('upserts and returns settings', async () => {
      const result = await upsert(baseSettings);
      expect(result).toEqual(baseSettings);
    });
  });
});
