import { createRouter, createWebHistory } from "vue-router";

import AppLayout from "../components/AppLayout.vue";
import { useAuthStore } from "../stores/auth";
import CommissionsView from "../views/CommissionsView.vue";
import ConfigCenterView from "../views/ConfigCenterView.vue";
import DashboardView from "../views/DashboardView.vue";
import EmployeesView from "../views/EmployeesView.vue";
import LoginView from "../views/LoginView.vue";
import MonthlyPayrollView from "../views/MonthlyPayrollView.vue";
import OperationLogsView from "../views/OperationLogsView.vue";
import OrganizationView from "../views/OrganizationView.vue";
import RealtimeAttendanceView from "../views/RealtimeAttendanceView.vue";
import ReportsView from "../views/ReportsView.vue";
import SalaryProfilesView from "../views/SalaryProfilesView.vue";
import UsersView from "../views/UsersView.vue";

declare module "vue-router" {
  interface RouteMeta {
    public?: boolean;
    permission?: string;
  }
}

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/login",
      name: "login",
      component: LoginView,
      meta: { public: true },
    },
    {
      path: "/",
      component: AppLayout,
      children: [
        {
          path: "",
          redirect: "/dashboard",
        },
        {
          path: "dashboard",
          name: "dashboard",
          component: DashboardView,
        },
        {
          path: "attendance/realtime",
          name: "attendance-realtime",
          component: RealtimeAttendanceView,
          meta: { permission: "attendance:realtime:view" },
        },
        {
          path: "payroll/monthly",
          name: "monthly-payroll",
          component: MonthlyPayrollView,
          meta: { permission: "monthly_payroll:view" },
        },
        {
          path: "payroll",
          name: "payroll",
          redirect: "/payroll/monthly",
        },
        {
          path: "payroll/jobs",
          name: "jobs",
          redirect: "/payroll/monthly",
          meta: { permission: "payroll:job:view" },
        },
        {
          path: "payroll/commissions",
          name: "commissions",
          component: CommissionsView,
          meta: { permission: "commission:view" },
        },
        {
          path: "reports",
          name: "reports",
          component: ReportsView,
          meta: { permission: "report:view" },
        },
        {
          path: "system/users",
          name: "users",
          component: UsersView,
          meta: { permission: "user:list" },
        },
        {
          path: "system/employees",
          name: "employees",
          component: EmployeesView,
          meta: { permission: "employee:view" },
        },
        {
          path: "system/organization",
          name: "organization",
          component: OrganizationView,
          meta: { permission: "organization:view" },
        },
        {
          path: "system/salary-profiles",
          name: "salary-profiles",
          component: SalaryProfilesView,
          meta: { permission: "salary_profile:view" },
        },
        {
          path: "system/configs",
          name: "configs",
          component: ConfigCenterView,
          meta: { permission: "config:view" },
        },
        {
          path: "system/operation-logs",
          name: "operation-logs",
          component: OperationLogsView,
          meta: { permission: "operation_log:view" },
        },
      ],
    },
    {
      path: "/:pathMatch(.*)*",
      redirect: "/dashboard",
    },
  ],
});

router.beforeEach(async (to) => {
  const auth = useAuthStore();

  if (!to.meta.public && !auth.loaded) {
    try {
      await auth.loadSession();
    } catch {
      auth.logout();
      return { path: "/login", query: { redirect: to.fullPath } };
    }
  }

  if (to.meta.public) {
    return auth.isAuthenticated ? "/dashboard" : true;
  }

  if (!auth.isAuthenticated) {
    return { path: "/login", query: { redirect: to.fullPath } };
  }

  const permission = to.meta.permission;
  if (permission && !auth.hasPermission(permission)) {
    return firstAllowedPath(auth.permissions);
  }

  return true;
});

function firstAllowedPath(permissions: string[]): string {
  if (permissions.includes("attendance:realtime:view")) {
    return "/attendance/realtime";
  }
  if (permissions.includes("monthly_payroll:view")) {
    return "/payroll/monthly";
  }
  if (permissions.includes("payroll:job:view")) {
    return "/payroll/monthly";
  }
  if (permissions.includes("commission:view")) {
    return "/payroll/commissions";
  }
  if (permissions.includes("report:view")) {
    return "/reports";
  }
  if (permissions.includes("user:list")) {
    return "/system/users";
  }
  if (permissions.includes("employee:view")) {
    return "/system/employees";
  }
  if (permissions.includes("organization:view")) {
    return "/system/organization";
  }
  if (permissions.includes("salary_profile:view")) {
    return "/system/salary-profiles";
  }
  if (permissions.includes("config:view")) {
    return "/system/configs";
  }
  if (permissions.includes("operation_log:view")) {
    return "/system/operation-logs";
  }
  return "/dashboard";
}

export default router;
