/**
 * Organization Management Types
 *
 * TypeScript types and constants for multi-staff dashboard organization management.
 * Defines roles, permissions, seat configurations, and invitation status.
 *
 * @module lib/types/organization.types
 */

// ============================================
// ENUMS
// ============================================

/**
 * Organization role hierarchy
 * - OWNER: Full control, billing access, can manage all staff
 * - ADMIN: Can manage staff, access all tabs except billing/team
 * - STAFF: Limited access to specific tabs only
 */
export type OrgRole = 'OWNER' | 'ADMIN' | 'STAFF';

/**
 * Invitation status states
 */
export type InvitationStatus = 'PENDING' | 'ACCEPTED' | 'EXPIRED' | 'REVOKED';

// ============================================
// INTERFACES
// ============================================

/**
 * Organization member with role and activity info
 */
export interface OrganizationMember {
  id: string;
  userId: string;
  email: string;
  name: string;
  role: OrgRole;
  joinedAt: Date;
  lastActiveAt?: Date;
}

/**
 * Staff member permissions based on role
 */
export interface StaffPermissions {
  canAccessAppointments: boolean;
  canAccessCustomers: boolean;
  canAccessWhatsApp: boolean;
  canAccessKnowledgeBase: boolean;
  canAccessAnalytics: boolean;
  canAccessWaitlists: boolean;
  canAccessWorkflows: boolean;
  canAccessLinks: boolean;
  canAccessSupport: boolean;
  canAccessBilling: boolean;
  canAccessTeam: boolean;
}

/**
 * Seat configuration for organization
 */
export interface SeatConfiguration {
  tierId: string;
  includedSeats: number;
  purchasedSeats: number;
  usedSeats: number;
  availableSeats: number;
}

/**
 * Organization invitation details
 */
export interface OrganizationInvitation {
  id: string;
  email: string;
  name?: string;
  role: OrgRole;
  status: InvitationStatus;
  expiresAt: Date;
  sentAt: Date;
  invitedBy?: string;
  token?: string;
}

/**
 * Organization details
 */
export interface Organization {
  id: string;
  name: string;
  ownerId: string;
  stripeCustomerId?: string;
  includedSeats: number;
  purchasedSeats: number;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// CONSTANTS
// ============================================

/**
 * Tier seat limits configuration
 * Tiers 1-2 have no multi-staff (0 seats)
 * Tier 3 (Business): 1 additional seat
 * Tier 4 (Enterprise): 2 additional seats
 * Tier 5 (Ultimate): 5 additional seats
 */
export const TIER_SEAT_LIMITS: Record<string, number> = {
  tier1: 0,
  tier2: 0,
  tier3: 1,
  tier4: 2,
  tier5: 5,
};

/**
 * Additional seat price in GBP per month
 */
export const ADDITIONAL_SEAT_PRICE_GBP = 9;

/**
 * Additional seat price in GBP per year (annual discount)
 */
export const ADDITIONAL_SEAT_PRICE_ANNUAL_GBP = 99; // ~17% discount vs monthly

/**
 * Additional seat price in QAR per month (GCC market primary currency)
 * Conversion: £9 GBP ≈ 42 QAR (rounded for clean pricing)
 */
export const ADDITIONAL_SEAT_PRICE_QAR = 42;

/**
 * Additional seat price in QAR per year (annual discount)
 * Conversion: £99 GBP ≈ 462 QAR (rounded for clean pricing)
 */
export const ADDITIONAL_SEAT_PRICE_ANNUAL_QAR = 462;

/**
 * Tab access permissions by role
 *
 * STAFF: Basic operational access only
 * - overview: Dashboard summary
 * - appointments: View/manage appointments
 * - customers: View/manage customer records
 * - whatsapp: Handle customer conversations
 * - waitlists: Add users to waitlists (operational task)
 *
 * Staff members do NOT have access to:
 * - billing: Financial data (owner only)
 * - team: Staff management (owner only)
 * - workflows: Automation setup (admin+)
 * - knowledge-base: AI training data (admin+)
 * - analytics: Business metrics (admin+)
 * - links: Booking links (admin+)
 * - support: Support tickets (admin+)
 */
export const STAFF_ALLOWED_TABS = [
  'overview',
  'appointments',
  'customers',
  'whatsapp',
  'quotations',
  'reviews',
  'support',
];

export const ADMIN_ALLOWED_TABS = [
  ...STAFF_ALLOWED_TABS,
  'knowledge-base',
  'voice-agent',
  'analytics',
  'reviews',
  'support',
  'quotations',
  'properties',
  'viewings',
  'brokers',
  'settings',
];

export const OWNER_ALLOWED_TABS = [
  ...ADMIN_ALLOWED_TABS,
  'billing',
  'team',
];

/**
 * Role hierarchy for permission checks
 */
export const ROLE_HIERARCHY: Record<OrgRole, number> = {
  STAFF: 1,
  ADMIN: 2,
  OWNER: 3,
};

// ============================================
// HELPER FUNCTIONS
// ============================================

/**
 * Get permissions for a given role
 */
export function getPermissionsForRole(role: OrgRole): StaffPermissions {
  const basePermissions: StaffPermissions = {
    canAccessAppointments: false,
    canAccessCustomers: false,
    canAccessWhatsApp: false,
    canAccessKnowledgeBase: false,
    canAccessAnalytics: false,
    canAccessWaitlists: false,
    canAccessWorkflows: false,
    canAccessLinks: false,
    canAccessSupport: false,
    canAccessBilling: false,
    canAccessTeam: false,
  };

  switch (role) {
    case 'OWNER':
      return {
        canAccessAppointments: true,
        canAccessCustomers: true,
        canAccessWhatsApp: true,
        canAccessKnowledgeBase: true,
        canAccessAnalytics: true,
        canAccessWaitlists: true,
        canAccessWorkflows: true,
        canAccessLinks: true,
        canAccessSupport: true,
        canAccessBilling: true,
        canAccessTeam: true,
      };

    case 'ADMIN':
      return {
        canAccessAppointments: true,
        canAccessCustomers: true,
        canAccessWhatsApp: true,
        canAccessKnowledgeBase: true,
        canAccessAnalytics: true,
        canAccessWaitlists: true,
        canAccessWorkflows: true,
        canAccessLinks: true,
        canAccessSupport: true,
        canAccessBilling: false,
        canAccessTeam: false,
      };

    case 'STAFF':
      // Staff members have basic operational access only
      // They can view/manage appointments, customers, WhatsApp conversations, and waitlists
      // They cannot access admin features like analytics, workflows, billing, etc.
      return {
        canAccessAppointments: true,
        canAccessCustomers: true,
        canAccessWhatsApp: true,
        canAccessKnowledgeBase: false, // Knowledge base is admin+ only
        canAccessAnalytics: false,
        canAccessWaitlists: true, // Staff can add users to waitlists
        canAccessWorkflows: false,
        canAccessLinks: false,
        canAccessSupport: false,
        canAccessBilling: false,
        canAccessTeam: false,
      };

    default:
      return basePermissions;
  }
}

/**
 * Check if role has permission for specific tab
 */
export function hasTabAccess(role: OrgRole, tab: string): boolean {
  switch (role) {
    case 'OWNER':
      return OWNER_ALLOWED_TABS.includes(tab);
    case 'ADMIN':
      return ADMIN_ALLOWED_TABS.includes(tab);
    case 'STAFF':
      return STAFF_ALLOWED_TABS.includes(tab);
    default:
      return false;
  }
}

/**
 * Check if one role has higher or equal permission than another
 */
export function hasRolePermission(userRole: OrgRole, requiredRole: OrgRole): boolean {
  return ROLE_HIERARCHY[userRole] >= ROLE_HIERARCHY[requiredRole];
}

/**
 * Calculate available seats for organization
 */
export function calculateAvailableSeats(
  tierId: string,
  purchasedSeats: number,
  usedSeats: number
): number {
  const includedSeats = TIER_SEAT_LIMITS[tierId] || 0;
  const totalSeats = includedSeats + purchasedSeats;
  return Math.max(0, totalSeats - usedSeats);
}

/**
 * Check if tier supports multi-staff
 */
export function tierSupportsMultiStaff(tierId: string): boolean {
  return (TIER_SEAT_LIMITS[tierId] || 0) > 0;
}

/**
 * Get seat configuration for organization
 */
export function getSeatConfiguration(
  tierId: string,
  purchasedSeats: number,
  usedSeats: number
): SeatConfiguration {
  const includedSeats = TIER_SEAT_LIMITS[tierId] || 0;
  const availableSeats = calculateAvailableSeats(tierId, purchasedSeats, usedSeats);

  return {
    tierId,
    includedSeats,
    purchasedSeats,
    usedSeats,
    availableSeats,
  };
}

/**
 * Validate role string
 */
export function isValidOrgRole(role: string): role is OrgRole {
  return ['OWNER', 'ADMIN', 'STAFF'].includes(role);
}

/**
 * Validate invitation status
 */
export function isValidInvitationStatus(status: string): status is InvitationStatus {
  return ['PENDING', 'ACCEPTED', 'EXPIRED', 'REVOKED'].includes(status);
}
