import type { ClientBrowser, ClientDevice, ClientRule } from './api';

export const DEVICE_OPTIONS: { value: string; label: string }[] = [
  { value: '', label: '不限制' },
  { value: 'mobile', label: '仅手机端可访问' },
  { value: 'desktop', label: '仅电脑端可访问' },
];

export const BROWSER_OPTIONS: { id: ClientBrowser; label: string }[] = [
  { id: 'chrome', label: 'Chrome' },
  { id: 'edge', label: 'Edge' },
  { id: 'safari', label: 'Safari' },
  { id: 'firefox', label: 'Firefox' },
  { id: 'opera', label: 'Opera' },
];

export function buildClientRule(device: string, selected: Set<ClientBrowser>): ClientRule | null {
  const d: ClientDevice | null = device === 'mobile' || device === 'desktop' ? device : null;
  const browsers = BROWSER_OPTIONS.filter(o => selected.has(o.id)).map(o => o.id);
  if (!d && browsers.length === 0) return null;
  return { device: d, browsers: browsers.length > 0 ? browsers : null };
}

export function parseClientRuleJson(raw: string | null | undefined): { device: string; selected: Set<ClientBrowser> } {
  if (!raw) return { device: '', selected: new Set() };
  try {
    const r = JSON.parse(raw) as ClientRule;
    const device = r.device === 'mobile' || r.device === 'desktop' ? r.device : '';
    const selected = new Set<ClientBrowser>();
    for (const b of r.browsers ?? []) {
      if (BROWSER_OPTIONS.some(o => o.id === b)) selected.add(b);
    }
    return { device, selected };
  } catch {
    return { device: '', selected: new Set() };
  }
}
