export type AuditTrailEntry = {
  id: string;
  timestamp: string;
  adminUser: string;
  actionType: string;
  module: string;
  ipAddress: string;
  severity: 'default' | 'alert';
  details: string;
};

export const AUDIT_TRAIL_STORAGE_KEY = 'bizone.audit.trail.v1';

export const seedAuditTrailEntries: AuditTrailEntry[] = [
  {
    id: 'audit_001',
    timestamp: '2026-05-09T07:12:05+07:00',
    adminUser: 'Sarah Wilson',
    actionType: 'Template Created',
    module: 'Marketing Logs',
    ipAddress: '192.168.1.45',
    severity: 'default',
    details: 'Created a new promo template for regional Eid campaign.',
  },
  {
    id: 'audit_002',
    timestamp: '2026-05-09T06:10:12+07:00',
    adminUser: 'John Smith',
    actionType: 'User Role Updated',
    module: 'Access Control',
    ipAddress: '45.23.11.102',
    severity: 'default',
    details: 'Updated access scope for campaign operators.',
  },
  {
    id: 'audit_003',
    timestamp: '2026-05-09T05:45:55+07:00',
    adminUser: 'Michael Chen',
    actionType: 'Webhook Modified',
    module: 'Integrations',
    ipAddress: '108.4.22.91',
    severity: 'default',
    details: 'Adjusted webhook signing secret and callback verification settings.',
  },
  {
    id: 'audit_004',
    timestamp: '2026-05-09T04:05:33+07:00',
    adminUser: 'SYSTEM_SEC',
    actionType: 'Failed Login Limit',
    module: 'Auth Gateway',
    ipAddress: '212.88.34.12',
    severity: 'alert',
    details: 'Security alert raised after repeated failed login attempts.',
  },
  {
    id: 'audit_005',
    timestamp: '2026-05-09T02:12:44+07:00',
    adminUser: 'Sarah Wilson',
    actionType: 'Profile Updated',
    module: 'Account',
    ipAddress: '192.168.1.45',
    severity: 'default',
    details: 'Updated profile identity and notification preferences.',
  },
];

export function readStoredAuditTrail(): AuditTrailEntry[] {
  if (typeof window === 'undefined') {
    return seedAuditTrailEntries;
  }

  const raw = window.localStorage.getItem(AUDIT_TRAIL_STORAGE_KEY);
  if (!raw) {
    return seedAuditTrailEntries;
  }

  try {
    const parsed = JSON.parse(raw) as AuditTrailEntry[];
    return Array.isArray(parsed) && parsed.length > 0 ? parsed : seedAuditTrailEntries;
  } catch {
    window.localStorage.removeItem(AUDIT_TRAIL_STORAGE_KEY);
    return seedAuditTrailEntries;
  }
}

export function writeStoredAuditTrail(entries: AuditTrailEntry[]) {
  if (typeof window === 'undefined') {
    return;
  }

  window.localStorage.setItem(AUDIT_TRAIL_STORAGE_KEY, JSON.stringify(entries));
}

export function appendAuditTrailEntry(entry: AuditTrailEntry) {
  if (typeof window === 'undefined') {
    return;
  }

  const entries = readStoredAuditTrail();
  writeStoredAuditTrail([entry, ...entries]);
}
