const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const { supabase } = require('../config/supabase');

/**
 * Middleware to verify JWT token
 */
function authMiddleware(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'No token provided' });
  }

  try {
    const token = authHeader.split(' ')[1];
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}

// Apply auth middleware to all routes
router.use(authMiddleware);

/**
 * GET /api/me/beneficiaries
 * Returns list of beneficiaries the user has access to
 */
router.get('/', async (req, res) => {
  try {
    const userId = req.user.userId;

    // Get access records first
    const { data: accessRecords, error: accessError } = await supabase
      .from('user_access')
      .select('id, beneficiary_id, role, granted_at')
      .eq('accessor_id', userId);

    if (accessError) {
      console.error('Get access records error:', accessError);
      return res.status(500).json({ error: 'Failed to get beneficiaries' });
    }

    if (!accessRecords || accessRecords.length === 0) {
      return res.json({ beneficiaries: [] });
    }

    // Get beneficiary details for each access record
    const beneficiaries = [];
    for (const record of accessRecords) {
      const { data: user } = await supabase
        .from('users')
        .select('id, email, first_name, last_name, phone, address_street, address_city, address_zip, address_state, address_country, created_at')
        .eq('id', record.beneficiary_id)
        .single();

      if (user) {
        beneficiaries.push({
          accessId: record.id,
          id: user.id,
          role: record.role,
          grantedAt: record.granted_at,
          email: user.email,
          firstName: user.first_name,
          lastName: user.last_name,
          phone: user.phone,
          address: {
            street: user.address_street,
            city: user.address_city,
            zip: user.address_zip,
            state: user.address_state,
            country: user.address_country
          },
          createdAt: user.created_at
        });
      }
    }

    res.json({ beneficiaries });

  } catch (error) {
    console.error('Get beneficiaries error:', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * GET /api/me/beneficiaries/:id
 * Returns details of a specific beneficiary
 */
router.get('/:id', async (req, res) => {
  try {
    const userId = req.user.userId;
    const beneficiaryId = parseInt(req.params.id, 10);

    // Check user has access
    const { data: access, error: accessError } = await supabase
      .from('user_access')
      .select('role')
      .eq('accessor_id', userId)
      .eq('beneficiary_id', beneficiaryId)
      .single();

    if (accessError || !access) {
      return res.status(403).json({ error: 'Access denied' });
    }

    // Get beneficiary details
    const { data: beneficiary, error } = await supabase
      .from('users')
      .select('*')
      .eq('id', beneficiaryId)
      .single();

    if (error || !beneficiary) {
      return res.status(404).json({ error: 'Beneficiary not found' });
    }

    // Get subscription for this beneficiary
    const { data: subscription } = await supabase
      .from('subscriptions')
      .select('*')
      .eq('beneficiary_id', beneficiaryId)
      .eq('user_id', userId)
      .single();

    // Get orders for this beneficiary
    const { data: orders } = await supabase
      .from('orders')
      .select('id, order_number, status, total_amount, created_at')
      .eq('beneficiary_id', beneficiaryId)
      .eq('user_id', userId)
      .order('created_at', { ascending: false });

    res.json({
      id: beneficiary.id,
      email: beneficiary.email,
      firstName: beneficiary.first_name,
      lastName: beneficiary.last_name,
      phone: beneficiary.phone,
      address: {
        street: beneficiary.address_street,
        city: beneficiary.address_city,
        zip: beneficiary.address_zip,
        state: beneficiary.address_state,
        country: beneficiary.address_country
      },
      role: access.role,
      subscription: subscription ? {
        plan: subscription.plan,
        status: subscription.status,
        currentPeriodEnd: subscription.current_period_end
      } : { plan: 'free', status: 'active' },
      orders: orders || []
    });

  } catch (error) {
    console.error('Get beneficiary error:', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * PATCH /api/me/beneficiaries/:id
 * Updates beneficiary info (requires owner role)
 */
router.patch('/:id', async (req, res) => {
  try {
    const userId = req.user.userId;
    const beneficiaryId = parseInt(req.params.id, 10);

    // Check user has owner access
    const { data: access, error: accessError } = await supabase
      .from('user_access')
      .select('role')
      .eq('accessor_id', userId)
      .eq('beneficiary_id', beneficiaryId)
      .single();

    if (accessError || !access || access.role !== 'owner') {
      return res.status(403).json({ error: 'Only owner can update beneficiary info' });
    }

    const { firstName, lastName, phone, addressStreet, addressCity, addressZip, addressState, addressCountry } = req.body;

    const updateData = {
      updated_at: new Date().toISOString()
    };

    if (firstName !== undefined) updateData.first_name = firstName;
    if (lastName !== undefined) updateData.last_name = lastName;
    if (phone !== undefined) updateData.phone = phone;
    if (addressStreet !== undefined) updateData.address_street = addressStreet;
    if (addressCity !== undefined) updateData.address_city = addressCity;
    if (addressZip !== undefined) updateData.address_zip = addressZip;
    if (addressState !== undefined) updateData.address_state = addressState;
    if (addressCountry !== undefined) updateData.address_country = addressCountry;

    const { data: beneficiary, error } = await supabase
      .from('users')
      .update(updateData)
      .eq('id', beneficiaryId)
      .select()
      .single();

    if (error) {
      return res.status(500).json({ error: 'Failed to update beneficiary' });
    }

    res.json({
      success: true,
      beneficiary: {
        id: beneficiary.id,
        email: beneficiary.email,
        firstName: beneficiary.first_name,
        lastName: beneficiary.last_name,
        phone: beneficiary.phone,
        address: {
          street: beneficiary.address_street,
          city: beneficiary.address_city,
          zip: beneficiary.address_zip,
          state: beneficiary.address_state,
          country: beneficiary.address_country
        }
      }
    });

  } catch (error) {
    console.error('Update beneficiary error:', error);
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
