// api.ts から分割（挙動不変）: ブラウザセッションプロファイル。
import { BASE, buildQuery } from './client';

// --- Browser Session Profiles ---
export interface BrowserSessionProfile {
  id: number;
  label: string;
  startUrl: string;
  matchPatterns: string[];
  storageOrigins: string[];
  loggedInSelector: string | null;
  loginUrlPatterns: string[];
  status: 'pending' | 'active' | 'expired' | 'revoked' | 'error';
  stateVersion: number;
  lastSavedAt: string | null;
  lastUsedAt: string | null;
  lastValidatedAt: string | null;
  lastError: string | null;
  createdAt: string;
  updatedAt: string;
  /** Owning space (null = legacy/personal). Surfaced for space-scoped listings. */
  spaceId?: string | null;
  /** The user who created the profile (its DEK owner). */
  ownerId?: string;
  /** False when the requesting viewer is NOT the owner: visible but unusable
   *  (the per-user DEK can only be decrypted by its owner). */
  decryptableByViewer?: boolean;
}

const SESS_BASE = `${BASE}/browser-sessions`;

export async function listBrowserSessionProfiles(spaceId?: string): Promise<BrowserSessionProfile[]> {
  const r = await fetch(`${SESS_BASE}/profiles${buildQuery({ spaceId })}`, { credentials: 'same-origin' });
  if (!r.ok) throw new Error(`listBrowserSessionProfiles: ${r.status}`);
  return (await r.json() as { profiles: BrowserSessionProfile[] }).profiles;
}

export async function createBrowserSessionProfile(
  input: Partial<BrowserSessionProfile> & { label: string; startUrl: string },
  spaceId?: string,
): Promise<BrowserSessionProfile> {
  const r = await fetch(`${SESS_BASE}/profiles${buildQuery({ spaceId })}`, {
    method: 'POST', credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(spaceId ? { ...input, spaceId } : input),
  });
  if (!r.ok) throw new Error(`createBrowserSessionProfile: ${r.status}`);
  return (await r.json() as { profile: BrowserSessionProfile }).profile;
}

export async function startBrowserSessionLogin(id: number): Promise<{ sessionId: string; novncPath: string }> {
  const r = await fetch(`${SESS_BASE}/profiles/${id}/login`, { method: 'POST', credentials: 'same-origin' });
  if (!r.ok) throw new Error((await r.text().catch(() => '')) || `startLogin: ${r.status}`);
  return r.json();
}

export async function saveBrowserSession(id: number, sessionId: string): Promise<BrowserSessionProfile> {
  const r = await fetch(`${SESS_BASE}/profiles/${id}/save`, {
    method: 'POST', credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ sessionId }),
  });
  if (!r.ok) throw new Error(`saveBrowserSession: ${r.status}`);
  return (await r.json() as { profile: BrowserSessionProfile }).profile;
}

export async function cancelBrowserSession(id: number, sessionId: string): Promise<void> {
  await fetch(`${SESS_BASE}/profiles/${id}/cancel`, {
    method: 'POST', credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ sessionId }),
  });
}

export async function testBrowserSessionProfile(id: number): Promise<{
  verdict: { expired: boolean; reason?: string };
  finalUrl: string;
  statusCode: number;
}> {
  const r = await fetch(`${SESS_BASE}/profiles/${id}/test`, { method: 'POST', credentials: 'same-origin' });
  if (!r.ok) throw new Error(`testBrowserSession: ${r.status}`);
  return r.json();
}

export async function deleteBrowserSessionProfile(id: number, spaceId?: string): Promise<void> {
  const r = await fetch(`${SESS_BASE}/profiles/${id}${buildQuery({ spaceId })}`, { method: 'DELETE', credentials: 'same-origin' });
  if (!r.ok) throw new Error(`deleteBrowserSessionProfile: ${r.status}`);
}
