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 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 Chance from 'chance';
const chance = new Chance();
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 {
    authorization: Authorization
  }
  type Authorization {
    try(input: AuthorizationTryInput): AuthorizationTryOutput
    set(input: AuthorizationSetInput): AuthorizationSetOutput
    get(input: AuthorizationGetInput): AuthorizationGetOutput
  }
  input AuthorizationTryInput {
    linkId: Int
  }
  type AuthorizationTryOutput {
    id: String
    error: String
  }
  input AuthorizationSetInput {
    id: String!
    linkId: Int
    error: String
  }
  type AuthorizationSetOutput {
    error: String
  }
  input AuthorizationGetInput {
    id: String!
  }
  type AuthorizationGetOutput {
    jwt: JWT
    error: String
  }
  type JWT {
    token: String
    linkId: Int
  }
`;
export const typeDefs = gql `${typeDefsString}`;
const tries = {};
const resolvers = {
    Query: {
        authorization: () => ({}),
    },
    Authorization: {
        try: (source, args, context, info) => __awaiter(void 0, void 0, void 0, function* () {
            var _a;
            const { linkId } = args.input;
            if (linkId && linkId !== +((_a = context === null || context === void 0 ? void 0 : context.headers) === null || _a === void 0 ? void 0 : _a['x-hasura-user-id'])) {
                return {
                    error: '!currentUser'
                };
            }
            const id = chance.string({ length: 16, pool: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' });
            tries[id] = {
                linkId,
                jwt: undefined,
            };
            return {
                id,
            };
        }),
        set: (source, args, context, info) => __awaiter(void 0, void 0, void 0, function* () {
            var _b, _c, _d;
            const { id, linkId: authLinkId, error } = args.input;
            if (!tries[id]) {
                return {
                    error: '!try'
                };
            }
            let { linkId } = tries[id];
            if (error) {
                tries[id].error = error;
                return;
            }
            let jwt;
            const auth = yield deep.select({
                type_id: deep.idLocal('@deep-foundation/core', 'Authorization'),
                to_id: authLinkId,
            });
            console.log('seeet', { jwt, auth: auth === null || auth === void 0 ? void 0 : auth.data, linkId });
            if ((_b = auth === null || auth === void 0 ? void 0 : auth.data) === null || _b === void 0 ? void 0 : _b.length) {
                console.log(`authorization already attached to link ${linkId}`);
                if (linkId) {
                    return {
                        error: `authorization already attached to link ${linkId}`,
                    };
                }
                else {
                    linkId = (_c = auth === null || auth === void 0 ? void 0 : auth.data) === null || _c === void 0 ? void 0 : _c[0].from_id;
                    jwt = yield deep.jwt({ linkId });
                }
            }
            else if (!((_d = auth === null || auth === void 0 ? void 0 : auth.data) === null || _d === void 0 ? void 0 : _d.length)) {
                if (!linkId) {
                    jwt = yield deep.guest();
                    linkId = jwt.linkId;
                }
                else {
                    jwt = yield deep.jwt({ linkId });
                }
                yield deep.insert({
                    type_id: deep.idLocal('@deep-foundation/core', 'Authorization'),
                    from_id: jwt.linkId,
                    to_id: authLinkId,
                });
            }
            tries[id].jwt = jwt;
            return {};
        }),
        get: (source, args, context, info) => __awaiter(void 0, void 0, void 0, function* () {
            var _e;
            const { id } = args.input;
            if (!tries[id]) {
                return {
                    error: '!try'
                };
            }
            const { linkId } = tries[id];
            if (linkId && linkId !== +((_e = context === null || context === void 0 ? void 0 : context.headers) === null || _e === void 0 ? void 0 : _e['x-hasura-user-id'])) {
                return {
                    error: '!currentUser'
                };
            }
            const jwt = tries[id].jwt;
            tries[id].jwt = undefined;
            return {
                jwt,
            };
        }),
    },
};
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=authorization.js.map