import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { wrapHandler, logError } from '../_shared/error-handler.ts'

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

function generateOTP(): string {
  return Math.floor(100000 + Math.random() * 900000).toString()
}

async function sendOTPEmail(email: string, otp: string, userName: string): Promise<{ success: boolean; error?: string }> {
  try {
    const resendApiKey = Deno.env.get('RESEND_API_KEY')

    if (!resendApiKey) {
      console.error('RESEND_API_KEY not configured')
      return { success: false, error: 'Email service not configured' }
    }

    const emailHtml = `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; border-radius: 10px; text-align: center; margin-bottom: 30px;">
          <h1 style="color: white; margin: 0; font-size: 2rem;">SHOPCALL.AI</h1>
          <p style="color: white; margin: 10px 0 0 0; opacity: 0.9;">Account Verification</p>
        </div>

        <div style="background: #f8f9fa; padding: 30px; border-radius: 10px; text-align: center;">
          <h2 style="color: #333; margin: 0 0 20px 0;">Hello ${userName}!</h2>
          <p style="color: #666; margin-bottom: 30px; font-size: 16px;">
            Please use the following verification code to complete your account setup:
          </p>

          <div style="background: white; border: 2px solid #667eea; border-radius: 10px; padding: 20px; margin: 20px 0; display: inline-block;">
            <div style="font-size: 32px; font-weight: bold; color: #667eea; letter-spacing: 5px;">${otp}</div>
          </div>

          <p style="color: #666; font-size: 14px; margin-top: 30px;">
            This code will expire in 15 minutes. If you didn't request this verification, please ignore this email.
          </p>
        </div>

        <div style="text-align: center; margin-top: 30px; color: #999; font-size: 12px;">
          <p>© 2024 ShopCall.ai. All rights reserved.</p>
        </div>
      </div>
    `

    const response = await fetch('https://api.resend.com/emails', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${resendApiKey}`
      },
      body: JSON.stringify({
        from: 'ShopCall.ai <onboarding@resend.dev>',
        to: [email],
        subject: 'Verify Your Account - ShopCall.ai',
        html: emailHtml
      })
    })

    if (!response.ok) {
      const errorData = await response.text()
      console.error('Resend API error:', errorData)
      return { success: false, error: 'Failed to send email' }
    }

    return { success: true }
  } catch (error) {
    console.error('Email sending error:', error)
    return { success: false, error: String(error) }
  }
}

serve(wrapHandler('auth', async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }
    const url = new URL(req.url)
    const path = url.pathname.replace('/auth/', '')

    const supabaseUrl = Deno.env.get('SUPABASE_URL')!
    const supabaseKey = Deno.env.get('SUPABASE_ANON_KEY')!
    const supabase = createClient(supabaseUrl, supabaseKey)

    if (path === 'signup' && req.method === 'POST') {
      const { full_name, company_name, user_name, email, password } = await req.json()

      if (!full_name || !company_name || !user_name || !email || !password) {
        return new Response(
          JSON.stringify({ error: 'All fields are required' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const otp = generateOTP()
      const signupId = crypto.randomUUID()

      const { error: insertError } = await supabase
        .from('pending_signups')
        .insert({
          signup_id: signupId,
          full_name,
          company_name,
          user_name,
          email,
          password,
          otp,
          expires_at: new Date(Date.now() + 15 * 60 * 1000).toISOString()
        })

      if (insertError) {
        console.error('Insert error:', insertError)
        return new Response(
          JSON.stringify({ error: 'Failed to create signup session' }),
          { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const emailResult = await sendOTPEmail(email, otp, full_name)

      if (!emailResult.success) {
        await supabase.from('pending_signups').delete().eq('signup_id', signupId)
        return new Response(
          JSON.stringify({ error: 'Failed to send verification email. Please try again.' }),
          { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      return new Response(
        JSON.stringify({
          success: true,
          message: 'OTP sent to your email. Please verify to complete registration.',
          signupId: signupId,
          requiresOtpVerification: true
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    } else if (path === 'signup/verify' && req.method === 'POST') {
      const { signupId, otp } = await req.json()

      if (!signupId || !otp) {
        return new Response(
          JSON.stringify({ error: 'Signup ID and OTP are required' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const { data: pendingData, error: fetchError } = await supabase
        .from('pending_signups')
        .select('*')
        .eq('signup_id', signupId)
        .single()

      if (fetchError || !pendingData) {
        return new Response(
          JSON.stringify({ error: 'Invalid or expired signup session' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      if (new Date() > new Date(pendingData.expires_at)) {
        await supabase.from('pending_signups').delete().eq('signup_id', signupId)
        return new Response(
          JSON.stringify({ error: 'Signup session expired. Please start again.' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      if (otp !== pendingData.otp) {
        return new Response(
          JSON.stringify({ error: 'Invalid OTP code' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const { data, error } = await supabase.auth.signUp({
        email: pendingData.email,
        password: pendingData.password,
        options: {
          data: {
            is_verified: true,
            full_name: pendingData.full_name,
            company_name: pendingData.company_name,
            user_name: pendingData.user_name
          }
        }
      })

      if (error) {
        return new Response(
          JSON.stringify({ error: error.message }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      await supabase.from('pending_signups').delete().eq('signup_id', signupId)

      return new Response(
        JSON.stringify({
          success: true,
          message: 'Account created successfully! You can now sign in.',
          user: data.user
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    } else if (path === 'signup/resend-otp' && req.method === 'POST') {
      const { signupId } = await req.json()

      if (!signupId) {
        return new Response(
          JSON.stringify({ error: 'Signup ID is required' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const { data: pendingData, error: fetchError } = await supabase
        .from('pending_signups')
        .select('*')
        .eq('signup_id', signupId)
        .single()

      if (fetchError || !pendingData) {
        return new Response(
          JSON.stringify({ error: 'Invalid or expired signup session' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      if (new Date() > new Date(pendingData.expires_at)) {
        await supabase.from('pending_signups').delete().eq('signup_id', signupId)
        return new Response(
          JSON.stringify({ error: 'Signup session expired. Please start again.' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const newOtp = generateOTP()

      await supabase
        .from('pending_signups')
        .update({ otp: newOtp })
        .eq('signup_id', signupId)

      const emailResult = await sendOTPEmail(pendingData.email, newOtp, pendingData.full_name)

      if (!emailResult.success) {
        return new Response(
          JSON.stringify({ error: 'Failed to send verification email' }),
          { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      return new Response(
        JSON.stringify({
          success: true,
          message: 'New OTP sent to your email'
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    } else if (path === 'login' && req.method === 'POST') {
      const { email, password } = await req.json()

      if (!email || !password) {
        return new Response(
          JSON.stringify({ error: 'Email and password are required' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const { data, error } = await supabase.auth.signInWithPassword({
        email,
        password
      })

      if (error) {
        return new Response(
          JSON.stringify({ error: 'Invalid email or password' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      return new Response(
        JSON.stringify({
          success: true,
          message: 'Login successful',
          user: data.user,
          session: data.session
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    } else if (path === 'logout' && req.method === 'POST') {
      const { error } = await supabase.auth.signOut()

      if (error) {
        return new Response(
          JSON.stringify({ error: error.message }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      return new Response(
        JSON.stringify({
          success: true,
          message: 'Logout successful'
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    } else if (path === 'check' && req.method === 'GET') {
      const authHeader = req.headers.get('authorization')
      if (!authHeader) {
        return new Response(
          JSON.stringify({ error: 'No authorization header' }),
          { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const token = authHeader.replace('Bearer ', '')
      const { data: { user }, error } = await supabase.auth.getUser(token)

      if (error || !user) {
        return new Response(
          JSON.stringify({ error: 'Invalid token' }),
          { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      return new Response(
        JSON.stringify({
          success: true,
          user: user
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    return new Response(
      JSON.stringify({ error: 'Not found' }),
      { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
}))
