import { z } from '@frontmcp/lazy-zod';
import { Tool, ToolContext } from '@frontmcp/sdk';

import { resolveDemoSessionId } from '../../resolve-session-id';
import { getSessionStore } from '../data/session.store';

const inputSchema = {
  key: z.string().describe('Key to store'),
  value: z.string().describe('Value to store'),
  ttlSeconds: z.number().int().positive().optional().describe('Time to live in seconds'),
};

const outputSchema = z
  .object({
    success: z.boolean(),
    key: z.string(),
    message: z.string(),
  })
  .strict();

@Tool({
  name: 'set-session-data',
  description: 'Store data in the session',
  inputSchema,
  outputSchema,
})
export default class SetSessionDataTool extends ToolContext {
  async execute(input: z.infer<z.ZodObject<typeof inputSchema>>): Promise<z.infer<typeof outputSchema>> {
    // Prefer FrontMcpContext.sessionId (always available in public mode) over authInfo.sessionId
    const ctx = this.tryGetContext();
    const sessionId = resolveDemoSessionId(ctx?.sessionId, this.getAuthInfo().sessionId);
    const store = getSessionStore(sessionId);

    store.set(input.key, input.value, input.ttlSeconds);

    return {
      success: true,
      key: input.key,
      message: `Stored key "${input.key}" in session ${sessionId}`,
    };
  }
}
