nama :

manage-user-credentials

code edge

import { serve } from "<https://deno.land/[email protected]/http/server.ts>"
import { createClient } from "<https://esm.sh/@supabase/[email protected]>"

const corsHeaders = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

serve(async (req) => {
    if (req.method === 'OPTIONS') {
        return new Response('ok', { headers: corsHeaders })
    }

    try {
        const supabaseClient = createClient(
            Deno.env.get('SUPABASE_URL') ?? '',
            Deno.env.get('SUPABASE_ANON_KEY') ?? '',
            { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
        )

        const {
            data: { user },
        } = await supabaseClient.auth.getUser()

        if (!user) {
            throw new Error('Unauthorized')
        }

        // Verify if the requester is an admin
        const { data: requesterProfile, error: profileError } = await supabaseClient
            .from('teachers')
            .select('role')
            .eq('id', user.id)
            .single()

        if (profileError || requesterProfile?.role !== 'admin') {
            throw new Error('Unauthorized: Admin access required')
        }

        const { userId, email, password, fullName } = await req.json()

        if (!userId) {
            throw new Error('User ID is required')
        }

        // Create Supabase client with Service Role Key to perform admin actions
        const supabaseAdmin = createClient(
            Deno.env.get('SUPABASE_URL') ?? '',
            Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
        )

        // Update Auth User
        const updates: any = {}
        if (email) updates.email = email
        if (password) updates.password = password
        // if (fullName) updates.user_metadata = { full_name: fullName } // Admin can update metadata too if needed

        if (Object.keys(updates).length > 0) {
            const { error: updateError } = await supabaseAdmin.auth.admin.updateUserById(
                userId,
                updates
            )

            if (updateError) throw updateError
        }

        // Update Public Table (teachers) if email or name changed
        // Note: The frontend might already be updating this, but doing it here ensures consistency
        // However, the prompt specifically asked for changing password/email.
        // Let's stick to Auth updates mainly, but if email changes, we MUST update the teachers table too ideally?
        // Actually, usually app logic relies on `auth.users` for login but `public.teachers` for display.
        // If we change email in Auth, we should probably check if we need to sync it to `public.teachers` manually or if there's a trigger.
        // Based on `TeacherManagement.jsx`, it seems `teachers` table has an `email` column?
        // Let's check `TeacherManagement.jsx` again. It has `email` in `formData` but `fetchTeachers` selects `*`.
        // The `teachers` table likely has an `email` column.

        // Let's sync the email to `public.teachers` if it's provided
        if (email) {
            const { error: dbError } = await supabaseAdmin
                .from('teachers')
                .update({ email: email }) // Assuming column is email
                .eq('id', userId)

            if (dbError) {
                // If the column doesn't exist, this will fail. Use introspection if unsure, 
                // but for now, based on filteredTeachers logic: `teacher.email?.toLowerCase`
                // it strongly suggests an email column exists.
                console.error("Failed to update email in teachers table:", dbError)
            }
        }

        return new Response(
            JSON.stringify({ message: 'User credentials updated successfully' }),
            {
                headers: { ...corsHeaders, 'Content-Type': 'application/json' },
                status: 200,
            }
        )
    } catch (error) {
        return new Response(
            JSON.stringify({ error: error.message }),
            {
                headers: { ...corsHeaders, 'Content-Type': 'application/json' },
                status: 400,
            }
        )
    }
})