import { Router, Request, Response } from 'express';
import { registerUser, loginUser, userAuthMiddleware } from './auth.service';
import { getDb } from '../database/database';
import { saveCloudConfig, deleteCloudConfig, testCloudConnectionWithCookie } from '../cloud/credential.service';
import { getAllCloudTypes } from '../cloud/cloud-types.service';

const router = Router();

// ── Public ──────────────────────────────────────────────────────

router.post('/register', (req: Request, res: Response) => {
  const { platform, phone, password } = req.body;
  // Support both new format (platform + phone) and legacy format (account)
  let account: string;
  if (platform && phone) {
    account = platform + '-' + phone;
  } else if (req.body.account) {
    account = req.body.account;
  } else {
    res.status(400).json({ error: '请选择推广平台并填写手机号' }); return;
  }
  if (!account || !password) { res.status(400).json({ error: '账号和密码不能为空' }); return; }
  if (password.length < 6) { res.status(400).json({ error: '密码至少6位' }); return; }
  const result = registerUser(account, password);
  if (result.success) res.json({ success: true, message: result.message, userId: result.userId });
  else res.status(400).json({ error: result.message });
});

router.post('/login', (req: Request, res: Response) => {
  const { account, password } = req.body;
  if (!account || !password) { res.status(400).json({ error: '账号和密码不能为空' }); return; }
  const result = loginUser(account, password);
  if (result.success) res.json({ success: true, token: result.token, message: result.message });
  else res.status(401).json({ error: result.message });
});

// ── Protected ───────────────────────────────────────────────────

router.use(userAuthMiddleware);

router.get('/profile', (req: Request, res: Response) => {
  const db = getDb();
  const user = db.prepare('SELECT id, account, role, notify_config, created_at FROM push_users WHERE id = ?').get(req.user!.userId) as any;
  if (!user) { res.status(404).json({ error: '用户不存在' }); return; }
  res.json({ id: user.id, account: user.account, role: user.role, notifyConfig: user.notify_config, createdAt: user.created_at });
});

// ── 转存日志 ──────────────────────────────────────────────────

router.get('/save-records', (req: Request, res: Response) => {
  const db = getDb();
  const page = Math.max(1, parseInt(String(req.query.page)) || 1);
  const pageSize = Math.min(100, Math.max(1, parseInt(String(req.query.pageSize)) || 20));
  const offset = (page - 1) * pageSize;
  const total = (db.prepare('SELECT COUNT(*) as count FROM save_records WHERE promotion_account = ?').get(req.user!.account) as any).count;
  const records = db.prepare(
    'SELECT id, source_type, source_title, source_url, share_url, share_pwd, file_size, file_count, folder_count, status, error_message, folder_name, duration_ms, created_at FROM save_records WHERE promotion_account = ? ORDER BY created_at DESC LIMIT ? OFFSET ?'
  ).all(req.user!.account, pageSize, offset);
  res.json({ total, page, pageSize, records });
});

// ── 网盘管理 ──────────────────────────────────────────────────

router.get('/cloud-configs', (req: Request, res: Response) => {
  const db = getDb();
  const configs = db.prepare(
    'SELECT id, cloud_type, nickname, cloud_type_uid, cookie_uid, promotion_account, storage_used, storage_total, is_active, verification_status, consecutive_failures, last_used_at, total_saves, created_at FROM cloud_configs WHERE promotion_account = ? AND is_active = 1 ORDER BY created_at DESC'
  ).all(req.user!.account);
  res.json(configs);
});

// Cookie 验证（保存前）
router.post('/cloud-configs/:cloudType/test', async (req: Request, res: Response) => {
  const { cookie } = req.body;
  if (!cookie) { res.status(400).json({ error: 'Cookie不能为空' }); return; }
  try {
    const result = await testCloudConnectionWithCookie(String(req.params.cloudType), cookie);
    res.json(result);
  } catch (e: any) { res.status(500).json({ error: e.message || '验证失败' }); }
});

router.post('/cloud-configs', (req: Request, res: Response) => {
  const { cloud_type, cookie, nickname, promotion_account } = req.body;
  if (!cloud_type || !cookie) { res.status(400).json({ error: '网盘类型和Cookie不能为空' }); return; }
  try {
    const config = saveCloudConfig({ cloud_type, cookie, nickname: nickname || '', promotion_account: promotion_account || req.user!.account, is_active: 0 });
    const { cookie: _, ...safe } = config as any;
    res.json(safe);
  } catch (e: any) { res.status(500).json({ error: e.message || '保存失败' }); }
});

router.put('/cloud-configs/:id', (req: Request, res: Response) => {
  const id = Number(req.params.id);
  const db = getDb();
  const existing = db.prepare('SELECT id FROM cloud_configs WHERE id = ? AND promotion_account = ?').get(id, req.user!.account) as any;
  if (!existing) { res.status(403).json({ error: '无权操作此网盘配置' }); return; }
  const { cloud_type, cookie, nickname, promotion_account } = req.body;
  try {
    const config = saveCloudConfig({ id, cloud_type: cloud_type || undefined, cookie: cookie || undefined, nickname, promotion_account: promotion_account || req.user!.account });
    const { cookie: _, ...safe } = config as any;
    res.json(safe);
  } catch (e: any) { res.status(500).json({ error: e.message || '保存失败' }); }
});

router.delete('/cloud-configs/:id', (req: Request, res: Response) => {
  const id = Number(req.params.id);
  const db = getDb();
  const existing = db.prepare('SELECT id FROM cloud_configs WHERE id = ? AND promotion_account = ?').get(id, req.user!.account) as any;
  if (!existing) { res.status(403).json({ error: '无权操作此网盘配置' }); return; }
  deleteCloudConfig(id);
  res.json({ success: true });
});

// ── 可用网盘类型（仅返回管理员已启用的） ──────────────────

router.get('/enabled-cloud-types', (_req: Request, res: Response) => {
  const allTypes = getAllCloudTypes();
  const enabled = allTypes.filter(ct => ct.enabled && ct.type !== 'others' && ct.type !== 'magnet' && ct.type !== 'ed2k');
  res.json(enabled);
});

// ── 推送配置 ──────────────────────────────────────────────────

router.get('/notify-config', (req: Request, res: Response) => {
  const db = getDb();
  const user = db.prepare('SELECT notify_config FROM push_users WHERE id = ?').get(req.user!.userId) as any;
  res.json({ notifyConfig: user?.notify_config || '{}' });
});

router.put('/notify-config', (req: Request, res: Response) => {
  const db = getDb();
  const { notifyConfig } = req.body;
  if (!notifyConfig) { res.status(400).json({ error: '推送配置不能为空' }); return; }
  db.prepare("UPDATE push_users SET notify_config = ?, updated_at = datetime('now','localtime') WHERE id = ?")
    .run(typeof notifyConfig === 'string' ? notifyConfig : JSON.stringify(notifyConfig), req.user!.userId);
  res.json({ success: true });
});

export default router;
