import { getSupabaseConfig } from '../storage/supabase-store.js';
const TESTIMONIALS_URL = (baseUrl) => `${baseUrl}/rest/v1/testimonials`;
function buildSupabaseHeaders(serviceRoleKey) {
    return {
        apikey: serviceRoleKey,
        Authorization: `Bearer ${serviceRoleKey}`,
        'Content-Type': 'application/json',
        Prefer: 'return=representation',
    };
}
function formatTestimonial(t) {
    const featured = t.featured ? ' [featured]' : '';
    const github = t.authorGithub ? ` (@${t.authorGithub})` : '';
    return `- "${t.quote}" — ${t.authorName}${github}, ${t.authorRole}${featured} (${t.rating}/5, ${t.locale})`;
}
export async function handleApproveTestimonial(input) {
    const config = await getSupabaseConfig(input.projectPath);
    if (!config) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Supabase not configured. Run configure_supabase first.',
                },
            ],
            isError: true,
        };
    }
    const hasFeedbackId = Boolean(input.feedbackId);
    const hasManualData = Boolean(input.authorName) && Boolean(input.quote);
    if (!hasFeedbackId && !hasManualData) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Validation failed: either feedbackId or both authorName and quote are required.',
                },
            ],
            isError: true,
        };
    }
    const payload = {
        author_name: input.authorName ?? '',
        author_role: input.authorRole ?? '',
        quote: input.quote ?? '',
        rating: input.rating ?? 5,
        source: input.source ?? 'manual',
        approved: true,
        featured: input.featured ?? false,
        locale: input.locale ?? 'en',
    };
    if (input.authorAvatarUrl !== undefined) {
        payload.author_avatar_url = input.authorAvatarUrl;
    }
    if (input.authorGithub !== undefined) {
        payload.author_github = input.authorGithub;
    }
    if (input.feedbackId !== undefined) {
        payload.feedback_id = input.feedbackId;
    }
    if (input.projectType !== undefined) {
        payload.project_type = input.projectType;
    }
    if (input.companySize !== undefined) {
        payload.company_size = input.companySize;
    }
    const response = await fetch(TESTIMONIALS_URL(config.projectUrl), {
        method: 'POST',
        headers: buildSupabaseHeaders(config.serviceRoleKey),
        body: JSON.stringify(payload),
    });
    if (!response.ok) {
        const errorText = await response.text();
        return {
            content: [
                {
                    type: 'text',
                    text: `Failed to insert testimonial (HTTP ${response.status}): ${errorText}. Check your Supabase config and that the testimonials table exists.`,
                },
            ],
            isError: true,
        };
    }
    const rows = (await response.json());
    const created = rows[0];
    const id = created?.id ?? 'unknown';
    return {
        content: [
            {
                type: 'text',
                text: `Testimonial approved and saved (id: ${id}).\nAuthor: ${input.authorName ?? '(from feedback)'}, rating: ${input.rating ?? 5}/5, featured: ${input.featured ?? false}.`,
            },
        ],
    };
}
export async function handleListTestimonials(input) {
    const config = await getSupabaseConfig(input.projectPath);
    if (!config) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Supabase not configured. Run configure_supabase first.',
                },
            ],
            isError: true,
        };
    }
    const filter = input.filter ?? 'approved';
    const limit = input.limit ?? 50;
    const params = new URLSearchParams({
        select: '*',
        order: 'created_at.desc',
        limit: String(limit),
    });
    if (filter === 'approved') {
        params.set('approved', 'eq.true');
    }
    else if (filter === 'pending') {
        params.set('approved', 'eq.false');
    }
    if (input.locale !== undefined) {
        params.set('locale', `eq.${input.locale}`);
    }
    if (input.featured === true) {
        params.set('featured', 'eq.true');
    }
    if (input.source !== undefined) {
        params.set('source', `eq.${input.source}`);
    }
    const url = `${TESTIMONIALS_URL(config.projectUrl)}?${params.toString()}`;
    const response = await fetch(url, {
        method: 'GET',
        headers: buildSupabaseHeaders(config.serviceRoleKey),
    });
    if (!response.ok) {
        const errorText = await response.text();
        return {
            content: [
                {
                    type: 'text',
                    text: `Failed to fetch testimonials (HTTP ${response.status}): ${errorText}. Check your Supabase config and that the testimonials table exists.`,
                },
            ],
            isError: true,
        };
    }
    const testimonials = (await response.json());
    if (testimonials.length === 0) {
        return {
            content: [
                {
                    type: 'text',
                    text: `No testimonials found (filter: ${filter}).`,
                },
            ],
        };
    }
    const lines = [
        `Testimonials (filter: ${filter}, count: ${testimonials.length}):`,
        ...testimonials.map(formatTestimonial),
    ];
    return {
        content: [{ type: 'text', text: lines.join('\n') }],
    };
}
//# sourceMappingURL=testimonial-handler.js.map