import type { MiddlewareHandler } from 'hono';
import type { Env } from '../env';
import { countUsers } from '../services/auth';

export const adminOnly: MiddlewareHandler<Env> = async (c, next) => {
  const user = c.get('currentUser');
  if (!user) {
    return c.redirect(`/login?next=${encodeURIComponent(c.req.path)}`);
  }
  if (user.role !== 'admin') return c.text('Forbidden', 403);
  await next();
};

export const adminApiOnly: MiddlewareHandler<Env> = async (c, next) => {
  const user = c.get('currentUser');
  if (!user) return c.json({ success: false, message: '请先登录', code: 'UNAUTHENTICATED' }, 401);
  if (user.role !== 'admin') return c.json({ success: false, message: '需要管理员权限', code: 'FORBIDDEN' }, 403);
  await next();
};

export async function shouldBootstrap(env: Env['Bindings']): Promise<boolean> {
  return (await countUsers(env.DB)) === 0;
}
