import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { Request, Response, NextFunction } from 'express';
import { getDb } from '../database/database';
import config from '../config';

// Use a separate secret for user JWT, fallback to main JWT secret
function getUserJwtSecret(): string {
  return config.jwtSecret;
}

export interface UserPayload {
  userId: number;
  account: string;
  role: string;
}

// Extend Express Request
declare global {
  namespace Express {
    interface Request {
      user?: UserPayload;
    }
  }
}

export function registerUser(account: string, password: string): { success: boolean; message: string; userId?: number } {
  const db = getDb();
  if (!db) return { success: false, message: '数据库未初始化' };

  // Validate account format: 平台-手机号
  if (!account || !account.includes('-')) {
    return { success: false, message: '账号格式：推广平台-手机号（如：蜂小推-13800138000）' };
  }

  // Check if already exists
  const existing = db.prepare('SELECT id FROM push_users WHERE account = ?').get(account) as any;
  if (existing && existing.password_hash) {
    return { success: false, message: '该账号已注册' };
  }

  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(password, salt);

  if (existing) {
    // Update existing push_user with password
    db.prepare('UPDATE push_users SET password_hash = ?, role = ? WHERE id = ?').run(hash, 'user', existing.id);
    return { success: true, message: '注册成功（已绑定已有推送账号）', userId: existing.id };
  } else {
    const result = db.prepare(
      "INSERT INTO push_users (account, password_hash, role, notify_config) VALUES (?, ?, 'user', '{}')"
    ).run(account, hash);
    return { success: true, message: '注册成功', userId: result.lastInsertRowid as number };
  }
}

export function loginUser(account: string, password: string): { success: boolean; message: string; token?: string } {
  const db = getDb();
  if (!db) return { success: false, message: '数据库未初始化' };

  const row = db.prepare('SELECT id, account, password_hash, role FROM push_users WHERE account = ?').get(account) as any;
  if (!row || !row.password_hash) {
    return { success: false, message: '账号不存在或未注册' };
  }

  if (!bcrypt.compareSync(password, row.password_hash)) {
    return { success: false, message: '密码错误' };
  }

  const payload: UserPayload = { userId: row.id, account: row.account, role: row.role || 'user' };
  const token = jwt.sign(payload, getUserJwtSecret(), { expiresIn: '7d' });

  return { success: true, message: '登录成功', token };
}

export function userAuthMiddleware(req: Request, res: Response, next: NextFunction): void {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    res.status(401).json({ error: '请先登录', code: 401 });
    return;
  }

  const token = authHeader.split(' ')[1];
  try {
    const decoded = jwt.verify(token, getUserJwtSecret()) as UserPayload;
    req.user = decoded;
    next();
  } catch {
    res.status(401).json({ error: '登录已过期，请重新登录', code: 401 });
  }
}
