// backend/src/routes/profile.js
import { Router } from 'express';
import { z } from 'zod';
import { query } from '../utils/db.js';
import { encrypt, decrypt } from '../utils/encryption.js';
import { requireAuth, requireActive } from '../middleware/auth.js';
import { testApiKey } from '../services/ai-provider.js';

const router = Router();

// GET /api/profile
router.get('/', requireAuth, async (req, res) => {
  const { rows } = await query('SELECT * FROM user_profiles WHERE user_id = $1', [req.user.id]);
  res.json(rows[0] || {});
});

// PUT /api/profile
router.put('/', requireAuth, async (req, res) => {
  const ProfileSchema = z.object({
    niche: z.string().max(200).optional(),
    brandName: z.string().max(100).optional(),
    targetAudience: z.string().max(300).optional(),
    tone: z.string().max(100).optional(),
    writingStyle: z.string().max(200).optional(),
    personality: z.string().max(300).optional(),
    avoidWords: z.array(z.string()).optional(),
    cta: z.string().max(200).optional(),
    examplePhrases: z.array(z.string()).optional(),
    scriptsPerDay: z.number().min(1).max(10).optional(),
    postsPerDay: z.number().min(1).max(10).optional(),
    newsletterFreq: z.enum(['daily', 'weekly']).optional(),
    outputTimezone: z.string().optional(),
  });

  try {
    const data = ProfileSchema.parse(req.body);
    await query(
      `INSERT INTO user_profiles (user_id, niche, brand_name, target_audience, tone, writing_style,
        personality, avoid_words, cta, example_phrases, scripts_per_day, posts_per_day,
        newsletter_freq, output_timezone)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
       ON CONFLICT (user_id) DO UPDATE SET
        niche=$2, brand_name=$3, target_audience=$4, tone=$5, writing_style=$6,
        personality=$7, avoid_words=$8, cta=$9, example_phrases=$10,
        scripts_per_day=$11, posts_per_day=$12, newsletter_freq=$13, output_timezone=$14,
        updated_at=NOW()`,
      [req.user.id, data.niche, data.brandName, data.targetAudience, data.tone,
       data.writingStyle, data.personality, data.avoidWords || [], data.cta,
       data.examplePhrases || [], data.scriptsPerDay, data.postsPerDay,
       data.newsletterFreq, data.outputTimezone]
    );
    res.json({ success: true });
  } catch (err) {
    if (err instanceof z.ZodError) return res.status(400).json({ error: 'validation', issues: err.issues });
    res.status(500).json({ error: 'server_error' });
  }
});

// GET /api/profile/api-keys
router.get('/api-keys', requireAuth, async (req, res) => {
  const { rows } = await query(
    'SELECT id, provider, model, is_valid, last_tested_at, created_at FROM user_api_keys WHERE user_id = $1',
    [req.user.id]
  );
  // Return masked keys (never expose decrypted)
  res.json(rows.map(r => ({ ...r, hasKey: true })));
});

// PUT /api/profile/api-keys/:provider
router.put('/api-keys/:provider', requireAuth, async (req, res) => {
  const { provider } = req.params;
  const { apiKey, model } = req.body;

  if (!['claude', 'openai', 'gemini'].includes(provider)) {
    return res.status(400).json({ error: 'Invalid provider' });
  }
  if (!apiKey || apiKey.length < 10) {
    return res.status(400).json({ error: 'Invalid API key' });
  }

  // Test the key before saving
  const testResult = await testApiKey(provider, apiKey, model);
  const encryptedKey = encrypt(apiKey);

  await query(
    `INSERT INTO user_api_keys (user_id, provider, encrypted_key, model, is_valid, last_tested_at)
     VALUES ($1, $2, $3, $4, $5, NOW())
     ON CONFLICT (user_id, provider) DO UPDATE SET
      encrypted_key=$3, model=$4, is_valid=$5, last_tested_at=NOW()`,
    [req.user.id, provider, encryptedKey, model, testResult.valid]
  );

  res.json({ success: true, valid: testResult.valid, error: testResult.error });
});

// DELETE /api/profile/api-keys/:provider
router.delete('/api-keys/:provider', requireAuth, async (req, res) => {
  await query('DELETE FROM user_api_keys WHERE user_id = $1 AND provider = $2', [req.user.id, req.params.provider]);
  res.json({ success: true });
});

// POST /api/profile/api-keys/:provider/test
router.post('/api-keys/:provider/test', requireAuth, async (req, res) => {
  const { rows } = await query(
    'SELECT encrypted_key, model FROM user_api_keys WHERE user_id = $1 AND provider = $2',
    [req.user.id, req.params.provider]
  );
  if (!rows[0]) return res.status(404).json({ error: 'Key not found' });

  const apiKey = decrypt(rows[0].encrypted_key);
  const result = await testApiKey(req.params.provider, apiKey, rows[0].model);

  await query(
    'UPDATE user_api_keys SET is_valid = $1, last_tested_at = NOW() WHERE user_id = $2 AND provider = $3',
    [result.valid, req.user.id, req.params.provider]
  );

  res.json(result);
});

export default router;
