import { router, protectedProcedure, publicProcedure } from "../_core/trpc.ts";
import { z } from "zod";
import {
  createSession,
  getSession,
  updateSessionActivity,
  destroySession,
  isSessionExpired,
  getSessionTimeout,
  refreshSession,
  getSessionInfo,
} from "../services/sessionManagement.ts";

export const sessionManagementRouter = router({
  // Get current session info
  getSessionInfo: protectedProcedure.query(async ({ ctx }) => {
    // Session info is available in context
    return {
      userId: ctx.user?.id,
      openId: ctx.user?.openId,
      email: ctx.user?.email,
      name: ctx.user?.name,
    };
  }),

  // Refresh session (extend timeout)
  refreshSession: protectedProcedure.mutation(async ({ ctx }) => {
    // In production, refresh the actual session token
    return {
      success: true,
      message: "Session refreshed",
    };
  }),

  // Check if session is still valid
  validateSession: protectedProcedure.query(async ({ ctx }) => {
    return {
      isValid: true,
      user: {
        id: ctx.user?.id,
        email: ctx.user?.email,
        name: ctx.user?.name,
      },
    };
  }),

  // Get session timeout remaining
  getSessionTimeout: protectedProcedure.query(async ({ ctx }) => {
    // Session timeout is managed by the session cookie
    // Return a default 30 minute timeout
    const SESSION_TIMEOUT_MS = 30 * 60 * 1000;
    return {
      timeoutMs: SESSION_TIMEOUT_MS,
      timeoutMinutes: 30,
    };
  }),

  // Logout (handled by auth router, but included here for completeness)
  logout: protectedProcedure.mutation(async ({ ctx }) => {
    return {
      success: true,
      message: "Logged out successfully",
    };
  }),
});
