/**
 * Role-based permission utilities for AV Beat
 * Mirrors the WordPress role structure exactly.
 */

export type BBRole = 'administrator' | 'admin' | 'editor' | 'author' | 'contributor' | 'reader';

export interface RolePermissions {
  canPublishDirectly: boolean;
  canEditOwnPosts: boolean;
  canDeleteOwnPosts: boolean;
  canEditAnyPost: boolean;
  canDeleteAnyPost: boolean;
  canPostToFeatured: boolean;
  canSeeFeaturedCategory: boolean;
  canManageUsers: boolean;
  canManageSettings: boolean;
  canManageAds: boolean;
  canManageAnalytics: boolean;
  canManageNewsletter: boolean;
  canManageBanners: boolean;
  canSchedulePosts: boolean;
  requiresReviewBeforePublish: boolean;
  canUploadMedia: boolean;
  canAccessAdminPanel: boolean;
}

const PERMISSIONS: Record<BBRole, RolePermissions> = {
  administrator: {
    canPublishDirectly: true,
    canEditOwnPosts: true,
    canDeleteOwnPosts: true,
    canEditAnyPost: true,
    canDeleteAnyPost: true,
    canPostToFeatured: true,
    canSeeFeaturedCategory: true,
    canManageUsers: true,
    canManageSettings: true,
    canManageAds: true,
    canManageAnalytics: true,
    canManageNewsletter: true,
    canManageBanners: true,
    canSchedulePosts: true,
    requiresReviewBeforePublish: false,
    canUploadMedia: true,
    canAccessAdminPanel: true,
  },
  admin: {
    canPublishDirectly: true,
    canEditOwnPosts: true,
    canDeleteOwnPosts: true,
    canEditAnyPost: true,
    canDeleteAnyPost: true,
    canPostToFeatured: true,
    canSeeFeaturedCategory: true,
    canManageUsers: true,
    canManageSettings: true,
    canManageAds: true,
    canManageAnalytics: true,
    canManageNewsletter: true,
    canManageBanners: true,
    canSchedulePosts: true,
    requiresReviewBeforePublish: false,
    canUploadMedia: true,
    canAccessAdminPanel: true,
  },
  editor: {
    canPublishDirectly: true,
    canEditOwnPosts: true,
    canDeleteOwnPosts: true,
    canEditAnyPost: true,
    canDeleteAnyPost: true,
    canPostToFeatured: true,
    canSeeFeaturedCategory: true,
    canManageUsers: false,
    canManageSettings: false,
    canManageAds: true,
    canManageAnalytics: true,
    canManageNewsletter: true,
    canManageBanners: true,
    canSchedulePosts: true,
    requiresReviewBeforePublish: false,
    canUploadMedia: true,
    canAccessAdminPanel: true,
  },
  author: {
    canPublishDirectly: true,
    canEditOwnPosts: true,
    canDeleteOwnPosts: true,
    canEditAnyPost: false,
    canDeleteAnyPost: false,
    canPostToFeatured: false,
    canSeeFeaturedCategory: false,
    canManageUsers: false,
    canManageSettings: false,
    canManageAds: false,
    canManageAnalytics: false,
    canManageNewsletter: false,
    canManageBanners: false,
    canSchedulePosts: true,
    requiresReviewBeforePublish: false,
    canUploadMedia: true,
    canAccessAdminPanel: false,
  },
  contributor: {
    canPublishDirectly: false,
    canEditOwnPosts: false,
    canDeleteOwnPosts: false,
    canEditAnyPost: false,
    canDeleteAnyPost: false,
    canPostToFeatured: false,
    canSeeFeaturedCategory: false,
    canManageUsers: false,
    canManageSettings: false,
    canManageAds: false,
    canManageAnalytics: false,
    canManageNewsletter: false,
    canManageBanners: false,
    canSchedulePosts: true,
    requiresReviewBeforePublish: true,
    canUploadMedia: false,
    canAccessAdminPanel: false,
  },
  reader: {
    canPublishDirectly: false,
    canEditOwnPosts: false,
    canDeleteOwnPosts: false,
    canEditAnyPost: false,
    canDeleteAnyPost: false,
    canPostToFeatured: false,
    canSeeFeaturedCategory: false,
    canManageUsers: false,
    canManageSettings: false,
    canManageAds: false,
    canManageAnalytics: false,
    canManageNewsletter: false,
    canManageBanners: false,
    canSchedulePosts: false,
    requiresReviewBeforePublish: true,
    canUploadMedia: false,
    canAccessAdminPanel: false,
  },
};

export function getPermissions(role: string): RolePermissions {
  return PERMISSIONS[role as BBRole] ?? PERMISSIONS.reader;
}

export function hasPermission(role: string, permission: keyof RolePermissions): boolean {
  return getPermissions(role)[permission] as boolean;
}

/**
 * Enforce Featured category lock.
 * Returns the safe category — strips Featured for contributor/author.
 */
export function enforceFeaturedCategoryLock(role: string, category: string): string {
  if (!hasPermission(role, 'canPostToFeatured') && category?.toLowerCase() === 'featured') {
    return 'Uncategorized';
  }
  return category;
}

/**
 * Determine the correct article status based on role and scheduling.
 */
export function determineArticleStatus(
  role: string,
  requestedStatus: string,
  scheduledAt: string | null
): string {
  const perms = getPermissions(role);

  if (scheduledAt) {
    if (perms.requiresReviewBeforePublish) {
      return 'scheduled_pending_review';
    }
    return 'scheduled';
  }

  if (perms.requiresReviewBeforePublish) {
    return 'pending';
  }

  if (perms.canPublishDirectly) {
    return requestedStatus || 'published';
  }

  return 'draft';
}

/**
 * Get the list of categories visible to a given role for a specific site.
 * Featured is hidden from contributor and author.
 */
export function getVisibleCategories(role: string, allCategories: string[]): string[] {
  if (!hasPermission(role, 'canSeeFeaturedCategory')) {
    return allCategories.filter(c => c.toLowerCase() !== 'featured');
  }
  return allCategories;
}

// ─── Multi-site support ───────────────────────────────────────────────────────

export const SITE_IDS = { BROADCAST_BEAT: 1, AV_BEAT: 2 } as const;

export const BB_CATEGORIES = [
  'Audio', 'Broadcast', 'Business', 'Camera', 'Cloud', 'Content Creation',
  'Distribution', 'Education', 'Events', 'IP & Networking', 'Live Production',
  'Media Management', 'News', 'OTT', 'Post Production', 'Radio',
  'Sports', 'Streaming', 'Technology', 'Uncategorized',
];

export const AV_CATEGORIES = [
  'AV Integration', 'Digital Signage', 'Unified Communications',
  'Streaming Technology', 'Conferencing & Collaboration', 'Houses of Worship',
  'Education AV', 'Control Systems', 'Display Technology', 'Sound & Audio',
  'Trade Shows & Events', 'Product News', 'Industry News',
];

export function getCategoriesForSite(role: string, siteId: number): string[] {
  const categories = siteId === SITE_IDS.AV_BEAT ? AV_CATEGORIES : BB_CATEGORIES;
  return getVisibleCategories(role, categories);
}

export const SITE_CONFIG = {
  [SITE_IDS.BROADCAST_BEAT]: { name: 'AV Beat', badge: 'BB', color: '#0ea5e9' },
  [SITE_IDS.AV_BEAT]:        { name: 'AV Beat',        badge: 'AV', color: '#f97316' },
} as const;

// ─── BB pen names (12 authorized writers — Section 15H / Conflict 4 resolved) ─
export const BB_PEN_NAMES = [
  'Michael Strand',
  'David Harlow',
  'Karen Fielding',
  'James Mercer',
  'Peter Calloway',
  'Sandra Voss',
  'Brian Kowalski',
  'Laura Pennington',
  'Thomas Reeves',
  'Christine Vale',
  'Marcus Webb',
  'Ellen Forsythe',
];

// ─── AV Beat pen names (7 authorized writers — Conflict 4 resolved) ──────────
export const AV_PEN_NAMES = [
  'Rex Chandler',
  'Dana Flux',
  'Derek Wainwright',
  'Sloane Rigging',
  'Chip Crosspoint',
  'Blair Presenter',
  'Jordan Lumen',
];

export function getPenNamesForSite(siteId: number): string[] {
  return siteId === SITE_IDS.AV_BEAT ? AV_PEN_NAMES : BB_PEN_NAMES;
}
