"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateMiddleware = generateMiddleware;
const Generator = __importStar(require("@postxl/generator"));
function generateMiddleware(context) {
    const imports = Generator.ImportGenerator.from(context.trpcRouter._middleware._filePath)
        .add(context.actions.summary.action)
        .add(context.actions.summary.resultOfActionHelper)
        .add(context.types.user)
        .add({ name: context.trpcRouter._shared.context.name, location: context.trpcRouter._shared._filePath })
        .add({ name: context.trpcRouter._shared.middleware.name, location: context.trpcRouter._shared._filePath });
    return /* ts */ `
  import { TRPCError } from '@trpc/server'
  ${imports.generate()}


/**
 * The shared context available to all routes after authentication.
 *
 * Contains the user and a dispatch function that already has the user set.
 */
export type ${context.trpcRouter._middleware.auth.context.name} = ${context.trpcRouter._shared.context.name} & {
  user: ${context.types.user.name}
  dispatch: <A extends ${context.actions.summary.action.name}>(action: A) => Promise<${context.actions.summary.resultOfActionHelper.name}<A>>
}  

/**
 * Middleware that ensures that a user was retrieved/is authenticated - otherwise, it throws an error.
 * For convenience, we expose the user in the context - as well as a dispatch function that already
 * has the user set.
 */
export const ${context.trpcRouter._middleware.auth.name} = ${context.trpcRouter._shared.middleware.name}(async ({ ctx, ...opts }) => {
  const viewer = ctx.viewer

  if (!viewer) {
    throw new TRPCError({ code: 'UNAUTHORIZED' })
  }

  const context: ${context.trpcRouter._middleware.auth.context.name} = {
    ...ctx,
    user: viewer.user,
    dispatch: <A extends ${context.actions.summary.action.name}>(action: A) => ctx.dispatcher.dispatch({ action, user: viewer.user }),
  }

  return opts.next({ ctx: context })
})

const _loggerMiddleware = ${context.trpcRouter._shared.middleware.name}(async (opts) => {
  const start = Date.now()

  const result = await opts.next()

  const durationMs = Date.now() - start
  const message = \`\${opts.type} - Path: \${opts.path} - duration: \${durationMs}\`
  if (opts.type !== 'query' || !result.ok) {
    if (result.ok) {
      opts.ctx.logger.log(message)
    } else {
      opts.ctx.logger.error(message)
    } 
  }

  return result
})
  `;
}
//# sourceMappingURL=middleware.generator.js.map