import { createSchema, createYoga } from 'graphql-yoga';
import { buildSchemaString } from './schema-builder.js';
import { buildResolvers } from './resolvers.js';
import { getDB } from '../db.js';
import { verifySession } from '../auth/session.js';
function parseCookieHeader(header) {
    const cookies = {};
    for (const pair of header.split(';')) {
        const [key, ...rest] = pair.split('=');
        if (key)
            cookies[key.trim()] = rest.join('=').trim();
    }
    return cookies;
}
export function createGraphQLHandler(options) {
    const typeDefs = buildSchemaString(options.config);
    const resolvers = buildResolvers(options.config);
    const yoga = createYoga({
        schema: createSchema({ typeDefs, resolvers }),
        graphqlEndpoint: '/api/cms/graphql',
        context: async ({ request }) => {
            let userId;
            let role = 'CLIENT';
            let token;
            const authHeader = request.headers.get('Authorization');
            if (authHeader?.startsWith('Bearer ')) {
                token = authHeader.slice(7);
            }
            if (!token) {
                const cookieHeader = request.headers.get('cookie') ?? '';
                const cookies = parseCookieHeader(cookieHeader);
                token = cookies['actuate_session'];
            }
            if (token) {
                try {
                    const payload = await verifySession(token, {
                        secret: options.secret,
                    });
                    const db = getDB();
                    const dbSession = await db.session.findUnique({
                        where: { id: payload.sessionId },
                        select: { revokedAt: true },
                    });
                    if (dbSession && !dbSession.revokedAt) {
                        userId = payload.userId;
                        role = payload.role;
                    }
                }
                catch {
                    /* unauthenticated */
                }
            }
            return { db: getDB(), userId, role };
        },
    });
    return yoga;
}
//# sourceMappingURL=index.js.map