// src/middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { decodeToken } from "@/lib/jwt";
import type { UserRole } from "@/types/auth";

function getUserRole(token: string | undefined): UserRole | null {
  if (!token) return null;

  const decodedToken = decodeToken(token);
  return decodedToken?.role || null;
}

export function middleware(request: NextRequest) {
  const token = request.cookies.get("token")?.value;

  // 비인증 사용자는 로그인 페이지로
  if (!token && !request.nextUrl.pathname.startsWith("/")) {
    return NextResponse.redirect(new URL("/", request.url));
  }

  // 권한별 접근 제어
  if (request.nextUrl.pathname.startsWith("/admin")) {
    const role = getUserRole(token);
    if (
      !role ||
      !["super_admin", "company_admin", "branch_admin", "user"].includes(role)
    ) {
      return NextResponse.redirect(new URL("/dashboard/overview", request.url));
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
