import { createRouter } from '../../create-router';
import { getUserSettings, setUserSettings, getUserState, patchUserState } from 'officerdb';
import { selfCapabilitiesRouter } from '../users/capabilities-routes';

const DEFAULT_SETTINGS = {
  chat: {
    defaultProvider: 'chat',
    defaultModel: null,
    systemPrompt: '',
    temperature: 1,
    defaultPwd: '~',
  },
  appearance: {
    theme: 'light',
  },
};

export const settingsRouter = createRouter();

// What the caller may reach. Under /api/user because it is a `core` capability — every account can ask
// what it is allowed to do, including an account that is allowed almost nothing.
settingsRouter.route('/', selfCapabilitiesRouter);

// GET /settings — return user settings from DB, default if empty
settingsRouter.get('/settings', async (ctx) => {
  const userId = ctx.get('user').id;
  const settings = await getUserSettings(userId);

  if (Object.keys(settings).length === 0) {
    await setUserSettings(userId, DEFAULT_SETTINGS);
    return ctx.json(DEFAULT_SETTINGS);
  }

  return ctx.json(settings);
});

// PUT /settings — full replacement
settingsRouter.put('/settings', async (ctx) => {
  const userId = ctx.get('user').id;
  const body = ctx.get('body');
  await setUserSettings(userId, body);
  return ctx.json(body);
});

// GET /state — return user state from DB
settingsRouter.get('/state', async (ctx) => {
  const userId = ctx.get('user').id;
  const state = await getUserState(userId);
  return ctx.json(state);
});

// PATCH /state — shallow-merge incoming keys
settingsRouter.patch('/state', async (ctx) => {
  const userId = ctx.get('user').id;
  const body = ctx.get('body');
  const merged = await patchUserState(userId, body);
  return ctx.json(merged);
});
