-- Fix account deletion flow: Critical schema improvements

-- 1. Drop old unique constraint and create new one that covers both pending and confirmed
DROP INDEX IF EXISTS unique_active_deletion_per_user;
CREATE UNIQUE INDEX unique_active_deletion_per_user 
ON account_deletion_requests(user_id) 
WHERE status IN ('pending', 'confirmed');

-- 2. Add indexes for efficient deletion processing
CREATE INDEX IF NOT EXISTS idx_account_deletions_confirmed 
ON account_deletion_requests(scheduled_deletion_at) 
WHERE status = 'confirmed';

CREATE INDEX IF NOT EXISTS idx_profiles_pending_deletion
ON profiles(user_id, deactivated) 
WHERE deactivated = true;

-- 3. Create security definer function for deletion checks (prevents infinite recursion in RLS)
CREATE OR REPLACE FUNCTION can_manage_deletion(
  _user_id uuid,
  _deletion_id uuid
)
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = public
AS $$
  SELECT EXISTS (
    SELECT 1 FROM account_deletion_requests
    WHERE id = _deletion_id 
    AND user_id = _user_id
    AND status IN ('pending', 'confirmed')
  )
$$;

-- 4. Update RLS policies to use security definer function
DROP POLICY IF EXISTS "Users can update their own deletion requests" ON account_deletion_requests;
DROP POLICY IF EXISTS "Users can view their own deletion requests" ON account_deletion_requests;

CREATE POLICY "Users can view their own deletion requests"
ON account_deletion_requests FOR SELECT
TO authenticated
USING (user_id = auth.uid());

CREATE POLICY "Users can update their own deletion requests"
ON account_deletion_requests FOR UPDATE
TO authenticated
USING (can_manage_deletion(auth.uid(), id))
WITH CHECK (can_manage_deletion(auth.uid(), id));