var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { jwt } from '../jwt.js';
import gql from 'graphql-tag';
import { ApolloServer } from 'apollo-server-express';
import { ApolloServerPluginDrainHttpServer, ApolloServerPluginLandingPageGraphQLPlayground } from 'apollo-server-core';
import { generateApolloClient } from '@deep-foundation/hasura/client.js';
import { DeepClient } from '../client.js';
import { serializeError } from 'serialize-error';
const apolloClient = generateApolloClient({
    path: `${process.env.DEEPLINKS_HASURA_PATH}/v1/graphql`,
    ssl: !!+process.env.DEEPLINKS_HASURA_SSL,
    secret: process.env.DEEPLINKS_HASURA_SECRET,
});
const deep = new DeepClient({ apolloClient });
const JWT_SECRET = process.env.JWT_SECRET;
const jwt_secret = JSON.parse(JWT_SECRET);
export const typeDefsString = `
  type Query {
    jwt(input: JWTInput): JWTOutput
  }
  input JWTInput {
    linkId: Int
  }
  type JWTOutput {
    token: String
    linkId: Int
    error: String
  }
`;
export const typeDefs = gql `${typeDefsString}`;
const resolvers = {
    Query: {
        jwt: (source, args, context, info) => __awaiter(void 0, void 0, void 0, function* () {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j;
            const { linkId } = args.input;
            try {
                if (!linkId) {
                    return {
                        linkId: +((_a = context === null || context === void 0 ? void 0 : context.headers) === null || _a === void 0 ? void 0 : _a['x-hasura-user-id'])
                    };
                }
                if (!+((_b = context === null || context === void 0 ? void 0 : context.headers) === null || _b === void 0 ? void 0 : _b['x-hasura-user-id']) && ((_c = context === null || context === void 0 ? void 0 : context.headers) === null || _c === void 0 ? void 0 : _c['x-hasura-role']) !== 'admin') {
                    return { error: '!currentUser' };
                }
                if (((_d = context === null || context === void 0 ? void 0 : context.headers) === null || _d === void 0 ? void 0 : _d['x-hasura-role']) !== 'admin' &&
                    !((_g = (_f = (yield deep.select({
                        subject_id: { _eq: +((_e = context === null || context === void 0 ? void 0 : context.headers) === null || _e === void 0 ? void 0 : _e['x-hasura-user-id']) },
                        action_id: { _eq: deep.idLocal('@deep-foundation/core', 'AllowAdmin') },
                    }, { table: 'can', returning: 'rule_id' }))) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g[0]) &&
                    +((_h = context === null || context === void 0 ? void 0 : context.headers) === null || _h === void 0 ? void 0 : _h['x-hasura-user-id']) !== linkId &&
                    !(yield deep.can(linkId, +((_j = context === null || context === void 0 ? void 0 : context.headers) === null || _j === void 0 ? void 0 : _j['x-hasura-user-id']), deep.idLocal('@deep-foundation/core', 'AllowLogin')))) {
                    return { error: 'cant' };
                }
                const token = jwt({
                    secret: jwt_secret.key,
                    linkId,
                    role: (yield deep.can(null, linkId, deep.idLocal('@deep-foundation/core', 'AllowAdmin'))) ? 'admin' : 'link',
                });
                return { token, linkId };
            }
            catch (error) {
                const serializedError = serializeError(error);
                return { serializedError };
            }
        }),
    }
};
const context = ({ req }) => {
    return { headers: req.headers };
};
const generateApolloServer = (httpServer) => {
    return new ApolloServer({
        introspection: true,
        typeDefs,
        resolvers,
        context,
        plugins: [
            ApolloServerPluginDrainHttpServer({ httpServer }),
            ApolloServerPluginLandingPageGraphQLPlayground()
        ]
    });
};
export default generateApolloServer;
//# sourceMappingURL=jwt.js.map