const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { query } = require('../utils/db');
const { requireFirebaseAuth } = require('../middleware/auth');

/**
 * POST /api/auth/sync
 * Called by Flutter after Firebase login.
 * Creates or updates the user record in PostgreSQL.
 * Returns a Mastreams user profile.
 */
router.post('/sync', requireFirebaseAuth, async (req, res) => {
  try {
    const { uid, email, name, picture } = req.user;

    // Upsert user — insert if new, update last_seen if existing
    const result = await query(`
      INSERT INTO users (firebase_uid, email, name, avatar_url, status)
      VALUES ($1, $2, $3, $4, 'active')
      ON CONFLICT (firebase_uid) DO UPDATE
        SET email      = EXCLUDED.email,
            name       = COALESCE(EXCLUDED.name, users.name),
            avatar_url = COALESCE(EXCLUDED.avatar_url, users.avatar_url),
            updated_at = NOW()
      RETURNING id, firebase_uid, email, name, avatar_url, phone, status, created_at
    `, [uid, email, name || null, picture || null]);

    res.json({ success: true, user: result.rows[0] });
  } catch (err) {
    console.error('Auth sync error:', err);
    res.status(500).json({ success: false, message: 'Failed to sync user' });
  }
});

/**
 * GET /api/auth/me
 * Returns current user profile from DB.
 */
router.get('/me', requireFirebaseAuth, async (req, res) => {
  try {
    const result = await query(
      'SELECT id, firebase_uid, email, name, avatar_url, phone, status, created_at FROM users WHERE firebase_uid = $1',
      [req.user.uid]
    );
    if (!result.rows.length) {
      return res.status(404).json({ success: false, message: 'User not found' });
    }
    res.json({ success: true, user: result.rows[0] });
  } catch (err) {
    res.status(500).json({ success: false, message: 'Failed to fetch user' });
  }
});

/**
 * PATCH /api/auth/me
 * Update user profile (name, phone).
 */
router.patch('/me', requireFirebaseAuth, async (req, res) => {
  try {
    const { name, phone } = req.body;
    const result = await query(
      `UPDATE users SET name = COALESCE($1, name), phone = COALESCE($2, phone), updated_at = NOW()
       WHERE firebase_uid = $3
       RETURNING id, email, name, avatar_url, phone, status`,
      [name || null, phone || null, req.user.uid]
    );
    res.json({ success: true, user: result.rows[0] });
  } catch (err) {
    res.status(500).json({ success: false, message: 'Failed to update profile' });
  }
});

// ─── Admin Auth ───────────────────────────────────────────────

/**
 * POST /api/auth/admin/login
 * Called by PHP admin panel to get a JWT.
 * Body: { email, password }
 */
router.post('/admin/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    if (!email || !password) {
      return res.status(400).json({ success: false, message: 'Email and password required' });
    }

    const result = await query(
      'SELECT id, email, password_hash, role, name FROM admins WHERE email = $1 AND is_active = true',
      [email.toLowerCase().trim()]
    );

    if (!result.rows.length) {
      return res.status(401).json({ success: false, message: 'Invalid credentials' });
    }

    const admin = result.rows[0];
    const valid = await bcrypt.compare(password, admin.password_hash);
    if (!valid) {
      return res.status(401).json({ success: false, message: 'Invalid credentials' });
    }

    const token = jwt.sign(
      { id: admin.id, email: admin.email, role: admin.role, name: admin.name },
      process.env.JWT_ADMIN_SECRET,
      { expiresIn: '12h' }
    );

    // Update last login
    await query('UPDATE admins SET last_login = NOW() WHERE id = $1', [admin.id]);

    res.json({
      success: true,
      token,
      admin: { id: admin.id, email: admin.email, role: admin.role, name: admin.name },
    });
  } catch (err) {
    console.error('Admin login error:', err);
    res.status(500).json({ success: false, message: 'Login failed' });
  }
});

/**
 * POST /api/auth/admin/create
 * One-time setup: create first admin account.
 * Remove or protect this route in production.
 */
router.post('/admin/create', async (req, res) => {
  try {
    const { email, password, name, setupKey } = req.body;

    // Protect with a one-time setup key from env
    if (setupKey !== process.env.ADMIN_SETUP_KEY) {
      return res.status(403).json({ success: false, message: 'Invalid setup key' });
    }

    const hash = await bcrypt.hash(password, 12);
    const result = await query(
      `INSERT INTO admins (email, password_hash, name, role)
       VALUES ($1, $2, $3, 'super_admin')
       RETURNING id, email, name, role`,
      [email.toLowerCase(), hash, name]
    );

    res.status(201).json({ success: true, admin: result.rows[0] });
  } catch (err) {
    if (err.code === '23505') {
      return res.status(409).json({ success: false, message: 'Admin with this email already exists' });
    }
    res.status(500).json({ success: false, message: 'Failed to create admin' });
  }
});

module.exports = router;
