// Predefined Report Definitions for ${BRAND.companyName}
// Each module has its own set of reports

export type ReportModule = 
  | 'finance' 
  | 'hr' 
  | 'sales' 
  | 'operations' 
  | 'compliance' 
  | 'inventory' 
  | 'marketing' 
  | 'executive';

export type ReportCategory = 
  | 'aging' 
  | 'summary' 
  | 'detail' 
  | 'trend' 
  | 'comparison' 
  | 'forecast' 
  | 'audit' 
  | 'kpi';

export type ReportType = 'tabular' | 'chart' | 'dashboard' | 'mixed';

export interface ReportColumn {
  key: string;
  label: string;
  type: 'string' | 'number' | 'currency' | 'date' | 'percentage' | 'boolean' | 'status';
  sortable?: boolean;
  filterable?: boolean;
  aggregation?: 'sum' | 'avg' | 'count' | 'min' | 'max';
  format?: string;
  width?: number;
}

export interface ReportFilter {
  key: string;
  label: string;
  type: 'select' | 'multiselect' | 'date' | 'daterange' | 'number' | 'text' | 'boolean';
  options?: { value: string; label: string }[];
  defaultValue?: unknown;
}

export interface ChartConfig {
  type: 'bar' | 'line' | 'pie' | 'area' | 'donut' | 'scatter' | 'radar' | 'gauge';
  xAxis?: string;
  yAxis?: string | string[];
  groupBy?: string;
  colors?: string[];
  showLegend?: boolean;
  showGrid?: boolean;
  stacked?: boolean;
}

export interface ReportDefinitionConfig {
  key: string;
  name: string;
  description: string;
  module: ReportModule;
  category: ReportCategory;
  reportType: ReportType;
  dataSource: string;
  queryConfig: Record<string, unknown>;
  defaultFilters: Record<string, unknown>;
  availableFilters: ReportFilter[];
  columns: ReportColumn[];
  chartConfig?: ChartConfig;
  permissions: string[];
  icon?: string;
  sortOrder: number;
}

// ============================================
// FINANCE MODULE REPORTS
// ============================================

const financeReports: ReportDefinitionConfig[] = [
  {
    key: 'ar_aging',
    name: 'Accounts Receivable Aging',
    description: 'Detailed breakdown of outstanding receivables by aging bucket',
    module: 'finance',
    category: 'aging',
    reportType: 'mixed',
    dataSource: 'Invoice',
    queryConfig: {
      include: ['customer'],
      where: { status: { not: 'PAID' } },
      groupBy: 'customer',
    },
    defaultFilters: {},
    availableFilters: [
      { key: 'customer', label: 'Customer', type: 'multiselect' },
      { key: 'dateRange', label: 'Invoice Date Range', type: 'daterange' },
      { key: 'minAmount', label: 'Min Amount', type: 'number' },
    ],
    columns: [
      { key: 'customerName', label: 'Customer', type: 'string', sortable: true },
      { key: 'current', label: 'Current', type: 'currency', aggregation: 'sum' },
      { key: 'days1_30', label: '1-30 Days', type: 'currency', aggregation: 'sum' },
      { key: 'days31_60', label: '31-60 Days', type: 'currency', aggregation: 'sum' },
      { key: 'days61_90', label: '61-90 Days', type: 'currency', aggregation: 'sum' },
      { key: 'over90', label: 'Over 90 Days', type: 'currency', aggregation: 'sum' },
      { key: 'total', label: 'Total', type: 'currency', aggregation: 'sum' },
    ],
    chartConfig: { type: 'bar', xAxis: 'customerName', yAxis: ['current', 'days1_30', 'days31_60', 'days61_90', 'over90'], stacked: true },
    permissions: ['finance', 'admin', 'executive'],
    icon: 'CreditCard',
    sortOrder: 1,
  },
  {
    key: 'ap_aging',
    name: 'Accounts Payable Aging',
    description: 'Outstanding payables breakdown by vendor and aging period',
    module: 'finance',
    category: 'aging',
    reportType: 'mixed',
    dataSource: 'Bill',
    queryConfig: {
      include: ['vendor'],
      where: { status: { not: 'PAID' } },
    },
    defaultFilters: {},
    availableFilters: [
      { key: 'vendor', label: 'Vendor', type: 'multiselect' },
      { key: 'dateRange', label: 'Bill Date Range', type: 'daterange' },
    ],
    columns: [
      { key: 'vendorName', label: 'Vendor', type: 'string', sortable: true },
      { key: 'current', label: 'Current', type: 'currency', aggregation: 'sum' },
      { key: 'days1_30', label: '1-30 Days', type: 'currency', aggregation: 'sum' },
      { key: 'days31_60', label: '31-60 Days', type: 'currency', aggregation: 'sum' },
      { key: 'days61_90', label: '61-90 Days', type: 'currency', aggregation: 'sum' },
      { key: 'over90', label: 'Over 90 Days', type: 'currency', aggregation: 'sum' },
      { key: 'total', label: 'Total', type: 'currency', aggregation: 'sum' },
    ],
    chartConfig: { type: 'bar', xAxis: 'vendorName', yAxis: 'total' },
    permissions: ['finance', 'admin', 'executive'],
    icon: 'Receipt',
    sortOrder: 2,
  },
  {
    key: 'cash_flow_statement',
    name: 'Cash Flow Statement',
    description: 'Monthly cash inflows and outflows with trends',
    module: 'finance',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'Transaction',
    queryConfig: { groupBy: 'month' },
    defaultFilters: { period: 'ytd' },
    availableFilters: [
      { key: 'period', label: 'Period', type: 'select', options: [
        { value: 'mtd', label: 'Month to Date' },
        { value: 'qtd', label: 'Quarter to Date' },
        { value: 'ytd', label: 'Year to Date' },
        { value: 'custom', label: 'Custom Range' },
      ]},
      { key: 'dateRange', label: 'Custom Date Range', type: 'daterange' },
    ],
    columns: [
      { key: 'period', label: 'Period', type: 'string' },
      { key: 'openingBalance', label: 'Opening Balance', type: 'currency' },
      { key: 'inflows', label: 'Inflows', type: 'currency', aggregation: 'sum' },
      { key: 'outflows', label: 'Outflows', type: 'currency', aggregation: 'sum' },
      { key: 'netCashFlow', label: 'Net Cash Flow', type: 'currency' },
      { key: 'closingBalance', label: 'Closing Balance', type: 'currency' },
    ],
    chartConfig: { type: 'area', xAxis: 'period', yAxis: ['inflows', 'outflows', 'netCashFlow'], showLegend: true },
    permissions: ['finance', 'admin', 'executive'],
    icon: 'TrendingUp',
    sortOrder: 3,
  },
  {
    key: 'revenue_by_customer',
    name: 'Revenue by Customer',
    description: 'Revenue breakdown by customer with YoY comparison',
    module: 'finance',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'Invoice',
    queryConfig: { where: { status: 'PAID' }, groupBy: 'customer' },
    defaultFilters: { period: 'ytd' },
    availableFilters: [
      { key: 'period', label: 'Period', type: 'select', options: [
        { value: 'mtd', label: 'Month to Date' },
        { value: 'qtd', label: 'Quarter to Date' },
        { value: 'ytd', label: 'Year to Date' },
      ]},
      { key: 'customer', label: 'Customer', type: 'multiselect' },
    ],
    columns: [
      { key: 'customerName', label: 'Customer', type: 'string', sortable: true },
      { key: 'revenue', label: 'Revenue', type: 'currency', aggregation: 'sum' },
      { key: 'invoiceCount', label: 'Invoices', type: 'number', aggregation: 'count' },
      { key: 'avgInvoice', label: 'Avg Invoice', type: 'currency' },
      { key: 'percentOfTotal', label: '% of Total', type: 'percentage' },
    ],
    chartConfig: { type: 'pie', groupBy: 'customerName' },
    permissions: ['finance', 'sales', 'admin', 'executive'],
    icon: 'PieChart',
    sortOrder: 4,
  },
  {
    key: 'profit_loss',
    name: 'Profit & Loss Statement',
    description: 'Income statement with revenue, expenses, and net profit',
    module: 'finance',
    category: 'summary',
    reportType: 'tabular',
    dataSource: 'GLAccount',
    queryConfig: { include: ['transactions'] },
    defaultFilters: { period: 'mtd' },
    availableFilters: [
      { key: 'period', label: 'Period', type: 'select', options: [
        { value: 'mtd', label: 'Month to Date' },
        { value: 'qtd', label: 'Quarter to Date' },
        { value: 'ytd', label: 'Year to Date' },
      ]},
      { key: 'compareWith', label: 'Compare With', type: 'select', options: [
        { value: 'none', label: 'No Comparison' },
        { value: 'prior_period', label: 'Prior Period' },
        { value: 'prior_year', label: 'Prior Year' },
        { value: 'budget', label: 'Budget' },
      ]},
    ],
    columns: [
      { key: 'account', label: 'Account', type: 'string' },
      { key: 'current', label: 'Current', type: 'currency' },
      { key: 'comparison', label: 'Comparison', type: 'currency' },
      { key: 'variance', label: 'Variance', type: 'currency' },
      { key: 'variancePercent', label: 'Var %', type: 'percentage' },
    ],
    permissions: ['finance', 'admin', 'executive'],
    icon: 'FileText',
    sortOrder: 5,
  },
  {
    key: 'daily_sales_summary',
    name: 'Daily Sales Summary',
    description: 'Daily breakdown of sales transactions',
    module: 'finance',
    category: 'detail',
    reportType: 'mixed',
    dataSource: 'SalesOrder',
    queryConfig: { groupBy: 'date' },
    defaultFilters: { period: 'last_30_days' },
    availableFilters: [
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
      { key: 'salesRep', label: 'Sales Rep', type: 'multiselect' },
    ],
    columns: [
      { key: 'date', label: 'Date', type: 'date', sortable: true },
      { key: 'orderCount', label: 'Orders', type: 'number', aggregation: 'count' },
      { key: 'grossSales', label: 'Gross Sales', type: 'currency', aggregation: 'sum' },
      { key: 'discounts', label: 'Discounts', type: 'currency', aggregation: 'sum' },
      { key: 'netSales', label: 'Net Sales', type: 'currency', aggregation: 'sum' },
    ],
    chartConfig: { type: 'line', xAxis: 'date', yAxis: 'netSales', showGrid: true },
    permissions: ['finance', 'sales', 'admin'],
    icon: 'Calendar',
    sortOrder: 6,
  },
  {
    key: 'bank_reconciliation',
    name: 'Bank Reconciliation Report',
    description: 'Bank statement reconciliation with matched/unmatched items',
    module: 'finance',
    category: 'detail',
    reportType: 'tabular',
    dataSource: 'BankTransaction',
    queryConfig: {},
    defaultFilters: { status: 'all' },
    availableFilters: [
      { key: 'bankAccount', label: 'Bank Account', type: 'select' },
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
      { key: 'status', label: 'Status', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'matched', label: 'Matched' },
        { value: 'unmatched', label: 'Unmatched' },
        { value: 'pending', label: 'Pending Review' },
      ]},
    ],
    columns: [
      { key: 'date', label: 'Date', type: 'date', sortable: true },
      { key: 'description', label: 'Description', type: 'string' },
      { key: 'amount', label: 'Amount', type: 'currency' },
      { key: 'matchedTo', label: 'Matched To', type: 'string' },
      { key: 'status', label: 'Status', type: 'status' },
    ],
    permissions: ['finance', 'admin'],
    icon: 'Building2',
    sortOrder: 7,
  },
];

// ============================================
// HR MODULE REPORTS
// ============================================

const hrReports: ReportDefinitionConfig[] = [
  {
    key: 'payroll_summary',
    name: 'Payroll Summary',
    description: 'Summary of payroll by period with totals and breakdowns',
    module: 'hr',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'PayrollRun',
    queryConfig: { include: ['payments'] },
    defaultFilters: {},
    availableFilters: [
      { key: 'period', label: 'Pay Period', type: 'select' },
      { key: 'department', label: 'Department', type: 'multiselect' },
    ],
    columns: [
      { key: 'period', label: 'Pay Period', type: 'string' },
      { key: 'employeeCount', label: 'Employees', type: 'number', aggregation: 'sum' },
      { key: 'totalGross', label: 'Gross Pay', type: 'currency', aggregation: 'sum' },
      { key: 'totalDeductions', label: 'Deductions', type: 'currency', aggregation: 'sum' },
      { key: 'totalNet', label: 'Net Pay', type: 'currency', aggregation: 'sum' },
      { key: 'status', label: 'Status', type: 'status' },
    ],
    chartConfig: { type: 'bar', xAxis: 'period', yAxis: ['totalGross', 'totalNet'] },
    permissions: ['hr', 'finance', 'admin', 'executive'],
    icon: 'Wallet',
    sortOrder: 1,
  },
  {
    key: 'employee_directory',
    name: 'Employee Directory',
    description: 'Complete list of employees with contact and department info',
    module: 'hr',
    category: 'detail',
    reportType: 'tabular',
    dataSource: 'Employee',
    queryConfig: { include: ['department'] },
    defaultFilters: { status: 'active' },
    availableFilters: [
      { key: 'department', label: 'Department', type: 'multiselect' },
      { key: 'status', label: 'Status', type: 'select', options: [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' },
        { value: 'all', label: 'All' },
      ]},
      { key: 'hireDate', label: 'Hire Date Range', type: 'daterange' },
    ],
    columns: [
      { key: 'employeeId', label: 'ID', type: 'string', sortable: true },
      { key: 'name', label: 'Name', type: 'string', sortable: true },
      { key: 'email', label: 'Email', type: 'string' },
      { key: 'department', label: 'Department', type: 'string', sortable: true },
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'hireDate', label: 'Hire Date', type: 'date', sortable: true },
      { key: 'status', label: 'Status', type: 'status' },
    ],
    permissions: ['hr', 'admin'],
    icon: 'Users',
    sortOrder: 2,
  },
  {
    key: 'headcount_by_department',
    name: 'Headcount by Department',
    description: 'Employee count breakdown by department with trends',
    module: 'hr',
    category: 'summary',
    reportType: 'chart',
    dataSource: 'Employee',
    queryConfig: { groupBy: 'department' },
    defaultFilters: { status: 'active' },
    availableFilters: [
      { key: 'status', label: 'Status', type: 'select', options: [
        { value: 'active', label: 'Active Only' },
        { value: 'all', label: 'All' },
      ]},
    ],
    columns: [
      { key: 'department', label: 'Department', type: 'string' },
      { key: 'count', label: 'Headcount', type: 'number', aggregation: 'count' },
      { key: 'percentOfTotal', label: '% of Total', type: 'percentage' },
    ],
    chartConfig: { type: 'pie', groupBy: 'department', showLegend: true },
    permissions: ['hr', 'admin', 'executive'],
    icon: 'Building',
    sortOrder: 3,
  },
  {
    key: 'time_off_balance',
    name: 'Time Off Balance',
    description: 'PTO/leave balances for all employees',
    module: 'hr',
    category: 'detail',
    reportType: 'tabular',
    dataSource: 'Employee',
    queryConfig: { include: ['timeOffBalances'] },
    defaultFilters: { status: 'active' },
    availableFilters: [
      { key: 'department', label: 'Department', type: 'multiselect' },
      { key: 'leaveType', label: 'Leave Type', type: 'select', options: [
        { value: 'pto', label: 'PTO' },
        { value: 'sick', label: 'Sick Leave' },
        { value: 'personal', label: 'Personal' },
      ]},
    ],
    columns: [
      { key: 'name', label: 'Employee', type: 'string', sortable: true },
      { key: 'department', label: 'Department', type: 'string' },
      { key: 'ptoBalance', label: 'PTO Balance', type: 'number' },
      { key: 'sickBalance', label: 'Sick Balance', type: 'number' },
      { key: 'usedThisYear', label: 'Used YTD', type: 'number' },
    ],
    permissions: ['hr', 'admin'],
    icon: 'CalendarDays',
    sortOrder: 4,
  },
  {
    key: 'turnover_analysis',
    name: 'Turnover Analysis',
    description: 'Employee turnover rates by department and period',
    module: 'hr',
    category: 'trend',
    reportType: 'mixed',
    dataSource: 'Employee',
    queryConfig: { include: ['terminations'] },
    defaultFilters: { period: 'ytd' },
    availableFilters: [
      { key: 'period', label: 'Period', type: 'select', options: [
        { value: 'qtd', label: 'Quarter to Date' },
        { value: 'ytd', label: 'Year to Date' },
        { value: 'last_12_months', label: 'Last 12 Months' },
      ]},
      { key: 'department', label: 'Department', type: 'multiselect' },
    ],
    columns: [
      { key: 'period', label: 'Period', type: 'string' },
      { key: 'department', label: 'Department', type: 'string' },
      { key: 'startingHeadcount', label: 'Starting', type: 'number' },
      { key: 'hires', label: 'Hires', type: 'number' },
      { key: 'terminations', label: 'Terms', type: 'number' },
      { key: 'endingHeadcount', label: 'Ending', type: 'number' },
      { key: 'turnoverRate', label: 'Turnover %', type: 'percentage' },
    ],
    chartConfig: { type: 'line', xAxis: 'period', yAxis: 'turnoverRate', showGrid: true },
    permissions: ['hr', 'admin', 'executive'],
    icon: 'UserMinus',
    sortOrder: 5,
  },
  {
    key: 'payroll_register',
    name: 'Payroll Register',
    description: 'Detailed payroll register with individual employee breakdowns',
    module: 'hr',
    category: 'detail',
    reportType: 'tabular',
    dataSource: 'PayrollPayment',
    queryConfig: { include: ['employee'] },
    defaultFilters: {},
    availableFilters: [
      { key: 'payPeriod', label: 'Pay Period', type: 'select' },
      { key: 'department', label: 'Department', type: 'multiselect' },
      { key: 'employee', label: 'Employee', type: 'multiselect' },
    ],
    columns: [
      { key: 'employeeName', label: 'Employee', type: 'string', sortable: true },
      { key: 'department', label: 'Department', type: 'string' },
      { key: 'grossPay', label: 'Gross Pay', type: 'currency', aggregation: 'sum' },
      { key: 'federalTax', label: 'Federal Tax', type: 'currency', aggregation: 'sum' },
      { key: 'stateTax', label: 'State Tax', type: 'currency', aggregation: 'sum' },
      { key: 'benefits', label: 'Benefits', type: 'currency', aggregation: 'sum' },
      { key: 'netPay', label: 'Net Pay', type: 'currency', aggregation: 'sum' },
    ],
    permissions: ['hr', 'finance', 'admin'],
    icon: 'FileSpreadsheet',
    sortOrder: 6,
  },
];

// ============================================
// SALES MODULE REPORTS
// ============================================

const salesReports: ReportDefinitionConfig[] = [
  {
    key: 'sales_pipeline',
    name: 'Sales Pipeline',
    description: 'Current pipeline by stage with conversion rates',
    module: 'sales',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'Opportunity',
    queryConfig: { groupBy: 'stage' },
    defaultFilters: { status: 'open' },
    availableFilters: [
      { key: 'status', label: 'Status', type: 'select', options: [
        { value: 'open', label: 'Open' },
        { value: 'won', label: 'Won' },
        { value: 'lost', label: 'Lost' },
        { value: 'all', label: 'All' },
      ]},
      { key: 'salesRep', label: 'Sales Rep', type: 'multiselect' },
      { key: 'closeDate', label: 'Expected Close', type: 'daterange' },
    ],
    columns: [
      { key: 'stage', label: 'Stage', type: 'string' },
      { key: 'count', label: 'Opportunities', type: 'number', aggregation: 'count' },
      { key: 'value', label: 'Pipeline Value', type: 'currency', aggregation: 'sum' },
      { key: 'avgDealSize', label: 'Avg Deal Size', type: 'currency' },
      { key: 'conversionRate', label: 'Conversion %', type: 'percentage' },
    ],
    chartConfig: { type: 'bar', xAxis: 'stage', yAxis: 'value' },
    permissions: ['sales', 'admin', 'executive'],
    icon: 'Target',
    sortOrder: 1,
  },
  {
    key: 'sales_by_rep',
    name: 'Sales by Rep',
    description: 'Performance breakdown by sales representative',
    module: 'sales',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'SalesOrder',
    queryConfig: { groupBy: 'salesRep' },
    defaultFilters: { period: 'mtd' },
    availableFilters: [
      { key: 'period', label: 'Period', type: 'select', options: [
        { value: 'mtd', label: 'Month to Date' },
        { value: 'qtd', label: 'Quarter to Date' },
        { value: 'ytd', label: 'Year to Date' },
      ]},
      { key: 'salesRep', label: 'Sales Rep', type: 'multiselect' },
    ],
    columns: [
      { key: 'salesRep', label: 'Sales Rep', type: 'string', sortable: true },
      { key: 'deals', label: 'Deals Closed', type: 'number', aggregation: 'count' },
      { key: 'revenue', label: 'Revenue', type: 'currency', aggregation: 'sum' },
      { key: 'quota', label: 'Quota', type: 'currency' },
      { key: 'attainment', label: 'Attainment %', type: 'percentage' },
    ],
    chartConfig: { type: 'bar', xAxis: 'salesRep', yAxis: ['revenue', 'quota'] },
    permissions: ['sales', 'admin', 'executive'],
    icon: 'UserCheck',
    sortOrder: 2,
  },
  {
    key: 'won_lost_analysis',
    name: 'Won/Lost Analysis',
    description: 'Analysis of won vs lost deals with reasons',
    module: 'sales',
    category: 'comparison',
    reportType: 'mixed',
    dataSource: 'Opportunity',
    queryConfig: { where: { status: { in: ['WON', 'LOST'] } } },
    defaultFilters: { period: 'last_90_days' },
    availableFilters: [
      { key: 'dateRange', label: 'Close Date', type: 'daterange' },
      { key: 'salesRep', label: 'Sales Rep', type: 'multiselect' },
    ],
    columns: [
      { key: 'reason', label: 'Win/Loss Reason', type: 'string' },
      { key: 'wonCount', label: 'Won', type: 'number', aggregation: 'sum' },
      { key: 'lostCount', label: 'Lost', type: 'number', aggregation: 'sum' },
      { key: 'wonValue', label: 'Won Value', type: 'currency', aggregation: 'sum' },
      { key: 'lostValue', label: 'Lost Value', type: 'currency', aggregation: 'sum' },
      { key: 'winRate', label: 'Win Rate', type: 'percentage' },
    ],
    chartConfig: { type: 'donut', groupBy: 'outcome', showLegend: true },
    permissions: ['sales', 'admin', 'executive'],
    icon: 'Scale',
    sortOrder: 3,
  },
  {
    key: 'sales_forecast',
    name: 'Sales Forecast',
    description: 'Weighted pipeline forecast by period',
    module: 'sales',
    category: 'forecast',
    reportType: 'mixed',
    dataSource: 'Opportunity',
    queryConfig: { where: { status: 'open' } },
    defaultFilters: {},
    availableFilters: [
      { key: 'forecastPeriod', label: 'Forecast Period', type: 'select', options: [
        { value: 'current_quarter', label: 'Current Quarter' },
        { value: 'next_quarter', label: 'Next Quarter' },
        { value: 'full_year', label: 'Full Year' },
      ]},
      { key: 'salesRep', label: 'Sales Rep', type: 'multiselect' },
    ],
    columns: [
      { key: 'period', label: 'Period', type: 'string' },
      { key: 'pipelineValue', label: 'Pipeline', type: 'currency', aggregation: 'sum' },
      { key: 'weightedValue', label: 'Weighted Forecast', type: 'currency', aggregation: 'sum' },
      { key: 'bestCase', label: 'Best Case', type: 'currency', aggregation: 'sum' },
      { key: 'worstCase', label: 'Worst Case', type: 'currency', aggregation: 'sum' },
    ],
    chartConfig: { type: 'bar', xAxis: 'period', yAxis: ['weightedValue', 'bestCase', 'worstCase'], stacked: false },
    permissions: ['sales', 'admin', 'executive'],
    icon: 'LineChart',
    sortOrder: 4,
  },
  {
    key: 'customer_acquisition',
    name: 'Customer Acquisition',
    description: 'New customer analysis with CAC and LTV',
    module: 'sales',
    category: 'trend',
    reportType: 'mixed',
    dataSource: 'Customer',
    queryConfig: { orderBy: { createdAt: 'desc' } },
    defaultFilters: { period: 'last_12_months' },
    availableFilters: [
      { key: 'period', label: 'Period', type: 'select', options: [
        { value: 'last_6_months', label: 'Last 6 Months' },
        { value: 'last_12_months', label: 'Last 12 Months' },
        { value: 'ytd', label: 'Year to Date' },
      ]},
      { key: 'source', label: 'Lead Source', type: 'multiselect' },
    ],
    columns: [
      { key: 'month', label: 'Month', type: 'string' },
      { key: 'newCustomers', label: 'New Customers', type: 'number', aggregation: 'count' },
      { key: 'totalRevenue', label: 'Revenue', type: 'currency', aggregation: 'sum' },
      { key: 'cac', label: 'CAC', type: 'currency' },
      { key: 'avgLtv', label: 'Avg LTV', type: 'currency' },
    ],
    chartConfig: { type: 'line', xAxis: 'month', yAxis: ['newCustomers', 'totalRevenue'], showGrid: true },
    permissions: ['sales', 'marketing', 'admin', 'executive'],
    icon: 'UserPlus',
    sortOrder: 5,
  },
];

// ============================================
// OPERATIONS MODULE REPORTS
// ============================================

const operationsReports: ReportDefinitionConfig[] = [
  {
    key: 'agent_performance',
    name: 'Agent Performance',
    description: 'AI agent task completion rates and accuracy',
    module: 'operations',
    category: 'kpi',
    reportType: 'mixed',
    dataSource: 'Agent',
    queryConfig: { include: ['tasks'] },
    defaultFilters: { period: 'last_7_days' },
    availableFilters: [
      { key: 'agent', label: 'Agent', type: 'multiselect' },
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
    ],
    columns: [
      { key: 'agentName', label: 'Agent', type: 'string', sortable: true },
      { key: 'tasksCompleted', label: 'Tasks Completed', type: 'number', aggregation: 'sum' },
      { key: 'successRate', label: 'Success Rate', type: 'percentage' },
      { key: 'avgDuration', label: 'Avg Duration', type: 'string' },
      { key: 'errorCount', label: 'Errors', type: 'number', aggregation: 'sum' },
    ],
    chartConfig: { type: 'bar', xAxis: 'agentName', yAxis: 'tasksCompleted' },
    permissions: ['operations', 'admin', 'executive'],
    icon: 'Bot',
    sortOrder: 1,
  },
  {
    key: 'workflow_efficiency',
    name: 'Workflow Efficiency',
    description: 'Workflow execution times and bottleneck analysis',
    module: 'operations',
    category: 'kpi',
    reportType: 'mixed',
    dataSource: 'WorkflowExecution',
    queryConfig: { include: ['workflow'] },
    defaultFilters: { period: 'last_30_days' },
    availableFilters: [
      { key: 'workflow', label: 'Workflow', type: 'multiselect' },
      { key: 'status', label: 'Status', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'completed', label: 'Completed' },
        { value: 'failed', label: 'Failed' },
      ]},
    ],
    columns: [
      { key: 'workflowName', label: 'Workflow', type: 'string', sortable: true },
      { key: 'executions', label: 'Executions', type: 'number', aggregation: 'count' },
      { key: 'avgDuration', label: 'Avg Duration', type: 'string' },
      { key: 'successRate', label: 'Success Rate', type: 'percentage' },
      { key: 'bottleneckStep', label: 'Bottleneck', type: 'string' },
    ],
    chartConfig: { type: 'bar', xAxis: 'workflowName', yAxis: 'avgDuration' },
    permissions: ['operations', 'admin'],
    icon: 'GitBranch',
    sortOrder: 2,
  },
  {
    key: 'task_completion',
    name: 'Task Completion Report',
    description: 'Detailed task completion status and SLA tracking',
    module: 'operations',
    category: 'detail',
    reportType: 'tabular',
    dataSource: 'Task',
    queryConfig: { orderBy: { createdAt: 'desc' } },
    defaultFilters: { status: 'all' },
    availableFilters: [
      { key: 'status', label: 'Status', type: 'multiselect', options: [
        { value: 'pending', label: 'Pending' },
        { value: 'in_progress', label: 'In Progress' },
        { value: 'completed', label: 'Completed' },
        { value: 'failed', label: 'Failed' },
      ]},
      { key: 'priority', label: 'Priority', type: 'select' },
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
    ],
    columns: [
      { key: 'taskId', label: 'Task ID', type: 'string' },
      { key: 'title', label: 'Title', type: 'string' },
      { key: 'assignedTo', label: 'Assigned To', type: 'string' },
      { key: 'status', label: 'Status', type: 'status' },
      { key: 'priority', label: 'Priority', type: 'string' },
      { key: 'dueDate', label: 'Due Date', type: 'date' },
      { key: 'completedAt', label: 'Completed', type: 'date' },
    ],
    permissions: ['operations', 'admin'],
    icon: 'CheckSquare',
    sortOrder: 3,
  },
  {
    key: 'system_health',
    name: 'System Health Dashboard',
    description: 'Real-time system health metrics and alerts',
    module: 'operations',
    category: 'kpi',
    reportType: 'dashboard',
    dataSource: 'HealthMetric',
    queryConfig: { orderBy: { timestamp: 'desc' }, take: 100 },
    defaultFilters: {},
    availableFilters: [
      { key: 'component', label: 'Component', type: 'multiselect' },
      { key: 'status', label: 'Status', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'healthy', label: 'Healthy' },
        { value: 'degraded', label: 'Degraded' },
        { value: 'critical', label: 'Critical' },
      ]},
    ],
    columns: [
      { key: 'component', label: 'Component', type: 'string' },
      { key: 'status', label: 'Status', type: 'status' },
      { key: 'uptime', label: 'Uptime', type: 'percentage' },
      { key: 'latency', label: 'Latency', type: 'string' },
      { key: 'lastHeartbeat', label: 'Last Heartbeat', type: 'date' },
    ],
    chartConfig: { type: 'gauge' },
    permissions: ['operations', 'admin'],
    icon: 'Activity',
    sortOrder: 4,
  },
  {
    key: 'error_analysis',
    name: 'Error Analysis',
    description: 'System errors grouped by type and frequency',
    module: 'operations',
    category: 'detail',
    reportType: 'mixed',
    dataSource: 'AuditLog',
    queryConfig: { where: { success: false } },
    defaultFilters: { period: 'last_7_days' },
    availableFilters: [
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
      { key: 'resource', label: 'Resource', type: 'multiselect' },
    ],
    columns: [
      { key: 'errorType', label: 'Error Type', type: 'string', sortable: true },
      { key: 'count', label: 'Count', type: 'number', aggregation: 'count' },
      { key: 'affectedResource', label: 'Affected Resource', type: 'string' },
      { key: 'lastOccurrence', label: 'Last Occurrence', type: 'date' },
      { key: 'trend', label: 'Trend', type: 'string' },
    ],
    chartConfig: { type: 'line', xAxis: 'date', yAxis: 'count', showGrid: true },
    permissions: ['operations', 'admin'],
    icon: 'AlertTriangle',
    sortOrder: 5,
  },
];

// ============================================
// COMPLIANCE MODULE REPORTS
// ============================================

const complianceReports: ReportDefinitionConfig[] = [
  {
    key: 'audit_log_summary',
    name: 'Audit Log Summary',
    description: 'Summary of all audit events by type and user',
    module: 'compliance',
    category: 'audit',
    reportType: 'mixed',
    dataSource: 'AuditLog',
    queryConfig: { orderBy: { timestamp: 'desc' } },
    defaultFilters: { period: 'last_30_days' },
    availableFilters: [
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
      { key: 'action', label: 'Action Type', type: 'multiselect' },
      { key: 'user', label: 'User', type: 'multiselect' },
      { key: 'success', label: 'Status', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'true', label: 'Success' },
        { value: 'false', label: 'Failed' },
      ]},
    ],
    columns: [
      { key: 'timestamp', label: 'Timestamp', type: 'date', sortable: true },
      { key: 'user', label: 'User', type: 'string' },
      { key: 'action', label: 'Action', type: 'string' },
      { key: 'resource', label: 'Resource', type: 'string' },
      { key: 'success', label: 'Status', type: 'status' },
      { key: 'details', label: 'Details', type: 'string' },
    ],
    chartConfig: { type: 'bar', xAxis: 'action', yAxis: 'count', stacked: false },
    permissions: ['compliance', 'admin', 'executive'],
    icon: 'ClipboardList',
    sortOrder: 1,
  },
  {
    key: 'access_review',
    name: 'Access Review Report',
    description: 'User access rights and permission audit',
    module: 'compliance',
    category: 'audit',
    reportType: 'tabular',
    dataSource: 'GfsUser',
    queryConfig: { include: ['roles'] },
    defaultFilters: {},
    availableFilters: [
      { key: 'role', label: 'Role', type: 'multiselect' },
      { key: 'department', label: 'Department', type: 'multiselect' },
      { key: 'status', label: 'Status', type: 'select', options: [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' },
        { value: 'all', label: 'All' },
      ]},
    ],
    columns: [
      { key: 'name', label: 'User', type: 'string', sortable: true },
      { key: 'email', label: 'Email', type: 'string' },
      { key: 'department', label: 'Department', type: 'string' },
      { key: 'roles', label: 'Roles', type: 'string' },
      { key: 'lastLogin', label: 'Last Login', type: 'date' },
      { key: 'status', label: 'Status', type: 'status' },
    ],
    permissions: ['compliance', 'admin'],
    icon: 'ShieldCheck',
    sortOrder: 2,
  },
  {
    key: 'security_events',
    name: 'Security Events',
    description: 'Security incidents and anomaly detection',
    module: 'compliance',
    category: 'audit',
    reportType: 'mixed',
    dataSource: 'SecurityEvent',
    queryConfig: { orderBy: { timestamp: 'desc' } },
    defaultFilters: { severity: 'all' },
    availableFilters: [
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
      { key: 'severity', label: 'Severity', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'low', label: 'Low' },
        { value: 'medium', label: 'Medium' },
        { value: 'high', label: 'High' },
        { value: 'critical', label: 'Critical' },
      ]},
      { key: 'eventType', label: 'Event Type', type: 'multiselect' },
    ],
    columns: [
      { key: 'timestamp', label: 'Timestamp', type: 'date', sortable: true },
      { key: 'eventType', label: 'Event Type', type: 'string' },
      { key: 'severity', label: 'Severity', type: 'status' },
      { key: 'user', label: 'User', type: 'string' },
      { key: 'description', label: 'Description', type: 'string' },
      { key: 'resolved', label: 'Resolved', type: 'boolean' },
    ],
    chartConfig: { type: 'bar', xAxis: 'eventType', yAxis: 'count' },
    permissions: ['compliance', 'admin'],
    icon: 'AlertOctagon',
    sortOrder: 3,
  },
  {
    key: 'data_retention',
    name: 'Data Retention Report',
    description: 'Data retention compliance and cleanup status',
    module: 'compliance',
    category: 'audit',
    reportType: 'tabular',
    dataSource: 'custom:data_retention',
    queryConfig: {},
    defaultFilters: {},
    availableFilters: [
      { key: 'dataType', label: 'Data Type', type: 'multiselect' },
      { key: 'status', label: 'Status', type: 'select', options: [
        { value: 'compliant', label: 'Compliant' },
        { value: 'attention', label: 'Needs Attention' },
        { value: 'overdue', label: 'Overdue' },
      ]},
    ],
    columns: [
      { key: 'dataType', label: 'Data Type', type: 'string' },
      { key: 'retentionPolicy', label: 'Policy', type: 'string' },
      { key: 'recordCount', label: 'Records', type: 'number' },
      { key: 'oldestRecord', label: 'Oldest', type: 'date' },
      { key: 'nextCleanup', label: 'Next Cleanup', type: 'date' },
      { key: 'status', label: 'Status', type: 'status' },
    ],
    permissions: ['compliance', 'admin'],
    icon: 'Database',
    sortOrder: 4,
  },
];

// ============================================
// INVENTORY MODULE REPORTS
// ============================================

const inventoryReports: ReportDefinitionConfig[] = [
  {
    key: 'stock_levels',
    name: 'Stock Level Report',
    description: 'Current inventory levels by location and SKU',
    module: 'inventory',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'InventoryItem',
    queryConfig: { include: ['location'] },
    defaultFilters: {},
    availableFilters: [
      { key: 'location', label: 'Location', type: 'multiselect' },
      { key: 'category', label: 'Category', type: 'multiselect' },
      { key: 'stockStatus', label: 'Stock Status', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'in_stock', label: 'In Stock' },
        { value: 'low_stock', label: 'Low Stock' },
        { value: 'out_of_stock', label: 'Out of Stock' },
      ]},
    ],
    columns: [
      { key: 'sku', label: 'SKU', type: 'string', sortable: true },
      { key: 'name', label: 'Product', type: 'string', sortable: true },
      { key: 'location', label: 'Location', type: 'string' },
      { key: 'quantity', label: 'Qty On Hand', type: 'number', aggregation: 'sum' },
      { key: 'reorderPoint', label: 'Reorder Point', type: 'number' },
      { key: 'status', label: 'Status', type: 'status' },
    ],
    chartConfig: { type: 'bar', xAxis: 'category', yAxis: 'quantity', stacked: false },
    permissions: ['inventory', 'operations', 'admin'],
    icon: 'Package',
    sortOrder: 1,
  },
  {
    key: 'reorder_alerts',
    name: 'Reorder Alerts',
    description: 'Items below reorder point requiring action',
    module: 'inventory',
    category: 'summary',
    reportType: 'tabular',
    dataSource: 'InventoryItem',
    queryConfig: { where: { quantity: { lte: 'reorderPoint' } } },
    defaultFilters: {},
    availableFilters: [
      { key: 'location', label: 'Location', type: 'multiselect' },
      { key: 'category', label: 'Category', type: 'multiselect' },
      { key: 'priority', label: 'Priority', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'critical', label: 'Critical' },
        { value: 'high', label: 'High' },
        { value: 'medium', label: 'Medium' },
      ]},
    ],
    columns: [
      { key: 'sku', label: 'SKU', type: 'string', sortable: true },
      { key: 'name', label: 'Product', type: 'string' },
      { key: 'quantity', label: 'Current Qty', type: 'number' },
      { key: 'reorderPoint', label: 'Reorder Point', type: 'number' },
      { key: 'suggestedOrder', label: 'Suggested Order', type: 'number' },
      { key: 'supplier', label: 'Supplier', type: 'string' },
      { key: 'priority', label: 'Priority', type: 'status' },
    ],
    permissions: ['inventory', 'operations', 'admin'],
    icon: 'AlertCircle',
    sortOrder: 2,
  },
  {
    key: 'inventory_valuation',
    name: 'Inventory Valuation',
    description: 'Total inventory value by category and location',
    module: 'inventory',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'InventoryItem',
    queryConfig: { groupBy: 'category' },
    defaultFilters: { valuationMethod: 'fifo' },
    availableFilters: [
      { key: 'location', label: 'Location', type: 'multiselect' },
      { key: 'category', label: 'Category', type: 'multiselect' },
      { key: 'valuationMethod', label: 'Valuation Method', type: 'select', options: [
        { value: 'fifo', label: 'FIFO' },
        { value: 'lifo', label: 'LIFO' },
        { value: 'average', label: 'Weighted Average' },
      ]},
    ],
    columns: [
      { key: 'category', label: 'Category', type: 'string', sortable: true },
      { key: 'itemCount', label: 'Items', type: 'number', aggregation: 'count' },
      { key: 'totalUnits', label: 'Total Units', type: 'number', aggregation: 'sum' },
      { key: 'totalValue', label: 'Total Value', type: 'currency', aggregation: 'sum' },
      { key: 'avgUnitCost', label: 'Avg Unit Cost', type: 'currency' },
    ],
    chartConfig: { type: 'pie', groupBy: 'category', showLegend: true },
    permissions: ['inventory', 'finance', 'admin'],
    icon: 'DollarSign',
    sortOrder: 3,
  },
  {
    key: 'inventory_movement',
    name: 'Inventory Movement',
    description: 'Stock movements (receipts, issues, transfers)',
    module: 'inventory',
    category: 'detail',
    reportType: 'tabular',
    dataSource: 'InventoryTransaction',
    queryConfig: { orderBy: { transactionDate: 'desc' } },
    defaultFilters: { period: 'last_30_days' },
    availableFilters: [
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
      { key: 'movementType', label: 'Movement Type', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'receipt', label: 'Receipts' },
        { value: 'issue', label: 'Issues' },
        { value: 'transfer', label: 'Transfers' },
        { value: 'adjustment', label: 'Adjustments' },
      ]},
      { key: 'sku', label: 'SKU', type: 'text' },
    ],
    columns: [
      { key: 'date', label: 'Date', type: 'date', sortable: true },
      { key: 'sku', label: 'SKU', type: 'string' },
      { key: 'product', label: 'Product', type: 'string' },
      { key: 'type', label: 'Type', type: 'string' },
      { key: 'quantity', label: 'Quantity', type: 'number' },
      { key: 'reference', label: 'Reference', type: 'string' },
      { key: 'location', label: 'Location', type: 'string' },
    ],
    permissions: ['inventory', 'operations', 'admin'],
    icon: 'ArrowRightLeft',
    sortOrder: 4,
  },
];

// ============================================
// MARKETING MODULE REPORTS
// ============================================

const marketingReports: ReportDefinitionConfig[] = [
  {
    key: 'campaign_performance',
    name: 'Campaign Performance',
    description: 'Marketing campaign metrics and ROI',
    module: 'marketing',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'Campaign',
    queryConfig: { include: ['leads', 'conversions'] },
    defaultFilters: { status: 'all' },
    availableFilters: [
      { key: 'status', label: 'Status', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'active', label: 'Active' },
        { value: 'completed', label: 'Completed' },
        { value: 'draft', label: 'Draft' },
      ]},
      { key: 'channel', label: 'Channel', type: 'multiselect' },
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
    ],
    columns: [
      { key: 'campaignName', label: 'Campaign', type: 'string', sortable: true },
      { key: 'channel', label: 'Channel', type: 'string' },
      { key: 'spend', label: 'Spend', type: 'currency', aggregation: 'sum' },
      { key: 'impressions', label: 'Impressions', type: 'number', aggregation: 'sum' },
      { key: 'clicks', label: 'Clicks', type: 'number', aggregation: 'sum' },
      { key: 'conversions', label: 'Conversions', type: 'number', aggregation: 'sum' },
      { key: 'cpa', label: 'CPA', type: 'currency' },
      { key: 'roi', label: 'ROI', type: 'percentage' },
    ],
    chartConfig: { type: 'bar', xAxis: 'campaignName', yAxis: ['spend', 'conversions'] },
    permissions: ['marketing', 'admin', 'executive'],
    icon: 'Megaphone',
    sortOrder: 1,
  },
  {
    key: 'lead_generation',
    name: 'Lead Generation Report',
    description: 'Lead sources and conversion funnel',
    module: 'marketing',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'Lead',
    queryConfig: { groupBy: 'source' },
    defaultFilters: { period: 'last_30_days' },
    availableFilters: [
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
      { key: 'source', label: 'Lead Source', type: 'multiselect' },
      { key: 'status', label: 'Status', type: 'multiselect' },
    ],
    columns: [
      { key: 'source', label: 'Source', type: 'string', sortable: true },
      { key: 'leads', label: 'Leads', type: 'number', aggregation: 'count' },
      { key: 'qualified', label: 'Qualified', type: 'number', aggregation: 'sum' },
      { key: 'converted', label: 'Converted', type: 'number', aggregation: 'sum' },
      { key: 'conversionRate', label: 'Conv Rate', type: 'percentage' },
      { key: 'costPerLead', label: 'CPL', type: 'currency' },
    ],
    chartConfig: { type: 'bar', xAxis: 'source', yAxis: ['leads', 'qualified', 'converted'], stacked: false },
    permissions: ['marketing', 'sales', 'admin'],
    icon: 'UserPlus',
    sortOrder: 2,
  },
  {
    key: 'email_analytics',
    name: 'Email Analytics',
    description: 'Email campaign open rates and engagement',
    module: 'marketing',
    category: 'detail',
    reportType: 'mixed',
    dataSource: 'EmailCampaign',
    queryConfig: { include: ['metrics'] },
    defaultFilters: { period: 'last_30_days' },
    availableFilters: [
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
      { key: 'campaign', label: 'Campaign', type: 'multiselect' },
    ],
    columns: [
      { key: 'campaignName', label: 'Campaign', type: 'string', sortable: true },
      { key: 'sent', label: 'Sent', type: 'number', aggregation: 'sum' },
      { key: 'delivered', label: 'Delivered', type: 'number', aggregation: 'sum' },
      { key: 'opened', label: 'Opened', type: 'number', aggregation: 'sum' },
      { key: 'clicked', label: 'Clicked', type: 'number', aggregation: 'sum' },
      { key: 'openRate', label: 'Open Rate', type: 'percentage' },
      { key: 'clickRate', label: 'Click Rate', type: 'percentage' },
    ],
    chartConfig: { type: 'line', xAxis: 'date', yAxis: ['openRate', 'clickRate'], showGrid: true },
    permissions: ['marketing', 'admin'],
    icon: 'Mail',
    sortOrder: 3,
  },
  {
    key: 'content_performance',
    name: 'Content Performance',
    description: 'Content engagement and traffic metrics',
    module: 'marketing',
    category: 'detail',
    reportType: 'mixed',
    dataSource: 'Content',
    queryConfig: { include: ['analytics'] },
    defaultFilters: { period: 'last_30_days' },
    availableFilters: [
      { key: 'contentType', label: 'Content Type', type: 'multiselect', options: [
        { value: 'blog', label: 'Blog Post' },
        { value: 'landing_page', label: 'Landing Page' },
        { value: 'video', label: 'Video' },
        { value: 'whitepaper', label: 'Whitepaper' },
      ]},
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
    ],
    columns: [
      { key: 'title', label: 'Content', type: 'string', sortable: true },
      { key: 'type', label: 'Type', type: 'string' },
      { key: 'views', label: 'Views', type: 'number', aggregation: 'sum' },
      { key: 'uniqueVisitors', label: 'Unique Visitors', type: 'number', aggregation: 'sum' },
      { key: 'avgTimeOnPage', label: 'Avg Time', type: 'string' },
      { key: 'bounceRate', label: 'Bounce Rate', type: 'percentage' },
      { key: 'conversions', label: 'Conversions', type: 'number', aggregation: 'sum' },
    ],
    chartConfig: { type: 'bar', xAxis: 'title', yAxis: 'views' },
    permissions: ['marketing', 'admin'],
    icon: 'FileText',
    sortOrder: 4,
  },
];

// ============================================
// EXECUTIVE MODULE REPORTS
// ============================================

const executiveReports: ReportDefinitionConfig[] = [
  {
    key: 'executive_dashboard',
    name: 'Executive Dashboard',
    description: 'High-level KPIs across all business functions',
    module: 'executive',
    category: 'kpi',
    reportType: 'dashboard',
    dataSource: 'custom:executive_kpis',
    queryConfig: {},
    defaultFilters: { period: 'mtd' },
    availableFilters: [
      { key: 'period', label: 'Period', type: 'select', options: [
        { value: 'mtd', label: 'Month to Date' },
        { value: 'qtd', label: 'Quarter to Date' },
        { value: 'ytd', label: 'Year to Date' },
      ]},
    ],
    columns: [
      { key: 'metric', label: 'Metric', type: 'string' },
      { key: 'current', label: 'Current', type: 'currency' },
      { key: 'prior', label: 'Prior Period', type: 'currency' },
      { key: 'target', label: 'Target', type: 'currency' },
      { key: 'variance', label: 'Variance', type: 'percentage' },
    ],
    permissions: ['executive', 'admin'],
    icon: 'LayoutDashboard',
    sortOrder: 1,
  },
  {
    key: 'weekly_brief',
    name: 'Weekly Intelligence Brief',
    description: 'Automated weekly summary of key metrics and insights',
    module: 'executive',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'IntelligenceBrief',
    queryConfig: { orderBy: { generatedAt: 'desc' }, take: 1 },
    defaultFilters: {},
    availableFilters: [
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
    ],
    columns: [
      { key: 'period', label: 'Period', type: 'string' },
      { key: 'executiveSummary', label: 'Summary', type: 'string' },
      { key: 'keyInsights', label: 'Key Insights', type: 'string' },
      { key: 'recommendations', label: 'Recommendations', type: 'string' },
    ],
    permissions: ['executive', 'admin'],
    icon: 'FileText',
    sortOrder: 2,
  },
  {
    key: 'financial_summary',
    name: 'Financial Summary',
    description: 'Revenue, expenses, and profitability overview',
    module: 'executive',
    category: 'summary',
    reportType: 'mixed',
    dataSource: 'custom:financial_summary',
    queryConfig: {},
    defaultFilters: { period: 'mtd' },
    availableFilters: [
      { key: 'period', label: 'Period', type: 'select', options: [
        { value: 'mtd', label: 'Month to Date' },
        { value: 'qtd', label: 'Quarter to Date' },
        { value: 'ytd', label: 'Year to Date' },
      ]},
      { key: 'compareWith', label: 'Compare With', type: 'select', options: [
        { value: 'prior_period', label: 'Prior Period' },
        { value: 'prior_year', label: 'Prior Year' },
        { value: 'budget', label: 'Budget' },
      ]},
    ],
    columns: [
      { key: 'category', label: 'Category', type: 'string' },
      { key: 'actual', label: 'Actual', type: 'currency', aggregation: 'sum' },
      { key: 'comparison', label: 'Comparison', type: 'currency', aggregation: 'sum' },
      { key: 'variance', label: 'Variance', type: 'currency' },
      { key: 'variancePercent', label: 'Var %', type: 'percentage' },
    ],
    chartConfig: { type: 'bar', xAxis: 'category', yAxis: ['actual', 'comparison'] },
    permissions: ['executive', 'finance', 'admin'],
    icon: 'DollarSign',
    sortOrder: 3,
  },
  {
    key: 'ops_health_summary',
    name: 'Operations Health Summary',
    description: 'Agent performance and automation efficiency',
    module: 'executive',
    category: 'kpi',
    reportType: 'mixed',
    dataSource: 'custom:ops_health',
    queryConfig: {},
    defaultFilters: { period: 'last_7_days' },
    availableFilters: [
      { key: 'period', label: 'Period', type: 'select', options: [
        { value: 'today', label: 'Today' },
        { value: 'last_7_days', label: 'Last 7 Days' },
        { value: 'last_30_days', label: 'Last 30 Days' },
      ]},
    ],
    columns: [
      { key: 'metric', label: 'Metric', type: 'string' },
      { key: 'value', label: 'Value', type: 'string' },
      { key: 'trend', label: 'Trend', type: 'string' },
      { key: 'status', label: 'Status', type: 'status' },
    ],
    chartConfig: { type: 'radar' },
    permissions: ['executive', 'operations', 'admin'],
    icon: 'Activity',
    sortOrder: 4,
  },
  {
    key: 'anomaly_digest',
    name: 'Anomaly Digest',
    description: 'AI-detected anomalies and proactive alerts',
    module: 'executive',
    category: 'audit',
    reportType: 'tabular',
    dataSource: 'custom:anomalies',
    queryConfig: {},
    defaultFilters: { severity: 'all', period: 'last_7_days' },
    availableFilters: [
      { key: 'severity', label: 'Severity', type: 'select', options: [
        { value: 'all', label: 'All' },
        { value: 'high', label: 'High' },
        { value: 'medium', label: 'Medium' },
        { value: 'low', label: 'Low' },
      ]},
      { key: 'category', label: 'Category', type: 'multiselect' },
      { key: 'dateRange', label: 'Date Range', type: 'daterange' },
    ],
    columns: [
      { key: 'detectedAt', label: 'Detected', type: 'date', sortable: true },
      { key: 'category', label: 'Category', type: 'string' },
      { key: 'description', label: 'Description', type: 'string' },
      { key: 'severity', label: 'Severity', type: 'status' },
      { key: 'status', label: 'Status', type: 'status' },
      { key: 'resolvedBy', label: 'Resolved By', type: 'string' },
    ],
    permissions: ['executive', 'admin'],
    icon: 'AlertTriangle',
    sortOrder: 5,
  },
];

// ============================================
// EXPORT ALL REPORTS
// ============================================

export const ALL_REPORT_DEFINITIONS: ReportDefinitionConfig[] = [
  ...financeReports,
  ...hrReports,
  ...salesReports,
  ...operationsReports,
  ...complianceReports,
  ...inventoryReports,
  ...marketingReports,
  ...executiveReports,
];

export const REPORTS_BY_MODULE: Record<ReportModule, ReportDefinitionConfig[]> = {
  finance: financeReports,
  hr: hrReports,
  sales: salesReports,
  operations: operationsReports,
  compliance: complianceReports,
  inventory: inventoryReports,
  marketing: marketingReports,
  executive: executiveReports,
};

export const MODULE_METADATA: Record<ReportModule, { name: string; description: string; icon: string; color: string }> = {
  finance: { name: 'Finance', description: 'Financial reports, AR/AP aging, cash flow', icon: 'Wallet', color: 'emerald' },
  hr: { name: 'Human Resources', description: 'Payroll, headcount, turnover', icon: 'Users', color: 'blue' },
  sales: { name: 'Sales', description: 'Pipeline, performance, forecasting', icon: 'Target', color: 'purple' },
  operations: { name: 'Operations', description: 'Agent performance, workflows, system health', icon: 'Cog', color: 'orange' },
  compliance: { name: 'Compliance', description: 'Audit logs, security, access reviews', icon: 'ShieldCheck', color: 'red' },
  inventory: { name: 'Inventory', description: 'Stock levels, valuation, movements', icon: 'Package', color: 'amber' },
  marketing: { name: 'Marketing', description: 'Campaigns, leads, content performance', icon: 'Megaphone', color: 'pink' },
  executive: { name: 'Executive', description: 'KPI dashboards, weekly briefs, summaries', icon: 'LayoutDashboard', color: 'cyan' },
};

// Initialize all report definitions in the database
export async function initializeReportDefinitions(prisma: PrismaClientType): Promise<void> {
  for (const report of ALL_REPORT_DEFINITIONS) {
    await prisma.reportDefinition.upsert({
      where: { key: report.key },
      update: {
        name: report.name,
        description: report.description,
        module: report.module,
        category: report.category,
        reportType: report.reportType,
        dataSource: report.dataSource,
        queryConfig: JSON.parse(JSON.stringify(report.queryConfig)),
        defaultFilters: JSON.parse(JSON.stringify(report.defaultFilters)),
        availableFilters: JSON.parse(JSON.stringify(report.availableFilters)),
        columns: JSON.parse(JSON.stringify(report.columns)),
        chartConfig: report.chartConfig ? JSON.parse(JSON.stringify(report.chartConfig)) : undefined,
        permissions: JSON.parse(JSON.stringify(report.permissions)),
        sortOrder: report.sortOrder,
        isActive: true,
        isSystem: true,
      },
      create: {
        key: report.key,
        name: report.name,
        description: report.description,
        module: report.module,
        category: report.category,
        reportType: report.reportType,
        dataSource: report.dataSource,
        queryConfig: JSON.parse(JSON.stringify(report.queryConfig)),
        defaultFilters: JSON.parse(JSON.stringify(report.defaultFilters)),
        availableFilters: JSON.parse(JSON.stringify(report.availableFilters)),
        columns: JSON.parse(JSON.stringify(report.columns)),
        chartConfig: report.chartConfig ? JSON.parse(JSON.stringify(report.chartConfig)) : undefined,
        permissions: JSON.parse(JSON.stringify(report.permissions)),
        sortOrder: report.sortOrder,
        isActive: true,
        isSystem: true,
      },
    });
  }
}

// Type for Prisma Client
import type { PrismaClient } from '@prisma/client';
import { BRAND } from '@/lib/white-label/constants';
type PrismaClientType = PrismaClient;
