import { pikkuSessionlessFunc } from '#pikku/pikku-types.gen.js';
import { BadRequestError } from '@pikku/core/errors';
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const FACILITY_TYPES = new Set([
    'krankenhaus',
    'altenpflege',
    'ambulant',
    'reha',
    'sonstige',
]);
const NURSES_NEEDED_RANGES = new Set(['1-5', '6-15', '16-30', '30+']);
const normalizeOptionalField = (value) => {
    const normalized = value?.trim();
    return normalized ? normalized : null;
};
const requireField = (value, label) => {
    const normalized = value.trim();
    if (!normalized) {
        throw new BadRequestError(`${label} is required`);
    }
    return normalized;
};
export const createLead = pikkuSessionlessFunc({
    auth: false,
    title: 'Create B2B lead',
    description: 'Stores a pilot landing page lead in the database',
    func: async ({ kysely }, data) => {
        const firstName = requireField(data.firstName, 'firstName');
        const lastName = requireField(data.lastName, 'lastName');
        const email = requireField(data.email, 'email').toLowerCase();
        const facilityName = requireField(data.facilityName, 'facilityName');
        const facilityType = requireField(data.facilityType, 'facilityType');
        const phone = normalizeOptionalField(data.phone);
        const nursesNeededRange = normalizeOptionalField(data.nursesNeededRange);
        const message = normalizeOptionalField(data.message);
        if (!EMAIL_REGEX.test(email)) {
            throw new BadRequestError('email is invalid');
        }
        if (!FACILITY_TYPES.has(facilityType)) {
            throw new BadRequestError('facilityType is invalid');
        }
        if (nursesNeededRange &&
            !NURSES_NEEDED_RANGES.has(nursesNeededRange)) {
            throw new BadRequestError('nursesNeededRange is invalid');
        }
        await kysely
            .insertInto('leads')
            .values({
            leadId: crypto.randomUUID(),
            firstName,
            lastName,
            email,
            phone,
            facilityName,
            facilityType,
            nursesNeededRange,
            message,
            source: 'pilot',
        })
            .executeTakeFirstOrThrow();
    },
});
//# sourceMappingURL=leads.functions.js.map