/**
 * Authentication and authorization types
 */

export interface AuthUser {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  roles: string[];
  accessToken: string;
  refreshToken?: string;
  expiresAt: number;
}

export interface TokenPayload {
  sub: string;
  email: string;
  given_name: string;
  family_name: string;
  realm_access?: {
    roles: string[];
  };
  resource_access?: {
    [clientId: string]: {
      roles: string[];
    };
  };
  iat: number;
  exp: number;
  iss: string;
  aud: string | string[];
}

export interface LoginRequest {
  username: string;
  password: string;
}

export interface RefreshTokenRequest {
  refreshToken: string;
}

export interface AuthResponse {
  accessToken: string;
  refreshToken: string;
  expiresIn: number;
  tokenType: 'Bearer';
}

export const PERMISSIONS = {
  USERS_READ: 'users:read',
  USERS_CREATE: 'users:create',
  USERS_UPDATE: 'users:update',
  USERS_DELETE: 'users:delete',
  DEPARTMENTS_READ: 'departments:read',
  DEPARTMENTS_MANAGE: 'departments:manage',
  EMPLOYEES_READ_ALL: 'employees:read:all',
  EMPLOYEES_READ_DEPARTMENT: 'employees:read:department',
  EMPLOYEES_READ_OWN: 'employees:read:own',
  EMPLOYEES_MANAGE: 'employees:manage',
  TIME_READ_ALL: 'time:read:all',
  TIME_READ_DEPARTMENT: 'time:read:department',
  TIME_READ_OWN: 'time:read:own',
  TIME_MANAGE: 'time:manage',
  ABSENCES_READ_ALL: 'absences:read:all',
  ABSENCES_READ_DEPARTMENT: 'absences:read:department',
  ABSENCES_READ_OWN: 'absences:read:own',
  ABSENCES_APPROVE: 'absences:approve',
  ABSENCES_CREATE: 'absences:create',
  LEAN_READ: 'lean:read',
  LEAN_MANAGE: 'lean:manage',
  INTEGRATIONS_READ: 'integrations:read',
  INTEGRATIONS_MANAGE: 'integrations:manage',
  ADMIN_ACCESS: 'admin:access',
  ADMIN_SYSTEM: 'admin:system',
} as const;

export type Permission = (typeof PERMISSIONS)[keyof typeof PERMISSIONS];

export const ROLE_PERMISSIONS: Record<string, Permission[]> = {
  admin: Object.values(PERMISSIONS),
  manager: [
    PERMISSIONS.USERS_READ,
    PERMISSIONS.DEPARTMENTS_READ,
    PERMISSIONS.EMPLOYEES_READ_ALL,
    PERMISSIONS.TIME_READ_ALL,
    PERMISSIONS.ABSENCES_READ_ALL,
    PERMISSIONS.ABSENCES_APPROVE,
    PERMISSIONS.LEAN_READ,
    PERMISSIONS.LEAN_MANAGE,
    PERMISSIONS.INTEGRATIONS_READ,
  ],
  department_head: [
    PERMISSIONS.USERS_READ,
    PERMISSIONS.DEPARTMENTS_READ,
    PERMISSIONS.EMPLOYEES_READ_DEPARTMENT,
    PERMISSIONS.TIME_READ_DEPARTMENT,
    PERMISSIONS.ABSENCES_READ_DEPARTMENT,
    PERMISSIONS.ABSENCES_APPROVE,
    PERMISSIONS.LEAN_READ,
    PERMISSIONS.LEAN_MANAGE,
  ],
  employee: [
    PERMISSIONS.EMPLOYEES_READ_OWN,
    PERMISSIONS.TIME_READ_OWN,
    PERMISSIONS.ABSENCES_READ_OWN,
    PERMISSIONS.ABSENCES_CREATE,
    PERMISSIONS.LEAN_READ,
  ],
};
