import { deleteServiceConnection, getServiceConnection, saveServiceConnection } from 'officerdb';
import { probe } from './rpc';
import {
  basicAuth,
  getTransmissionConfig,
  invalidateTransmissionConfig,
  normalizeBase,
  normalizeRpcPath,
} from './upstream';

// `/_config` — where the Transmission daemon is, driven from the app rather than from a shell on the server.
//
// ONE connection, not a registry: nobody runs two Transmission daemons. So there is no label, no id in the
// path and no activate route — a save is an upsert over the single row, and the UI is one form.
//
// The URL is the only thing usually needed. Most Transmission daemons run with no RPC auth at all, so
// username/password are optional and an EMPTY username means "no auth" rather than "empty credentials" —
// see basicAuth in upstream.ts, where sending a Basic header anyway makes the daemon reject the request.
// `rpcPath` is there for the reverse-proxy case and defaults to /transmission/rpc.
//
// The password is WRITE-ONLY across this boundary: the GET reports whether one is stored, never its value.
// A save is validated with a live session-get first, so a wrong URL or rejected credentials is a 400 with
// the reason rather than a stored row that makes every later screen fail mysteriously.

/** What the browser is allowed to know about the connection. Never includes the password. */
async function connectionState(userId: number): Promise<Response> {
  const connection = await getServiceConnection(userId, 'transmission');
  return Response.json({ configured: !!connection, connection });
}

const bad = (error: string, status = 400) => Response.json({ error }, { status });

type ConnectionBody = { url?: unknown; username?: unknown; password?: unknown; rpcPath?: unknown };

const isHttpUrl = (url: string): boolean => /^https?:\/\//i.test(url);

const readString = (value: unknown): string => (typeof value === 'string' ? value.trim() : '');

/** Save the connection: validated against the live daemon, then stored. */
async function save(req: Request, userId: number): Promise<Response> {
  const body = ((await req.json().catch(() => null)) as ConnectionBody | null) ?? {};
  const url = typeof body.url === 'string' ? normalizeBase(body.url) : '';
  const username = readString(body.username);
  const rpcPath = normalizeRpcPath(readString(body.rpcPath));
  // A blank password with a username still set means "keep the stored one", so changing the URL does not
  // need the password re-typed. Clearing the username clears the auth entirely.
  const password = typeof body.password === 'string' && body.password ? body.password : null;

  if (!url) return bad('url is required');
  if (!isHttpUrl(url)) return bad('url must start with http:// or https://');

  const current = await getServiceConnection(userId, 'transmission');
  const keepPassword = !password && !!username && username === current?.username && current.hasSecret;

  // Probing needs the real password, so a save that keeps the stored one borrows it through the normal read
  // path rather than reaching for the ciphertext here.
  const stored = keepPassword ? await getTransmissionConfig(userId) : null;
  const auth = keepPassword ? (stored?.auth ?? null) : basicAuth(username || null, password);

  const result = await probe({ base: url, rpcPath, auth });
  if (!result.ok) return bad(result.error ?? 'could not reach the daemon');

  const connection = await saveServiceConnection({
    userId,
    service: 'transmission',
    url,
    username: username || null,
    // undefined keeps the stored password; null clears it, which is what dropping the username means.
    secret: keepPassword ? undefined : (password ?? null),
    path: rpcPath,
    version: result.version ?? null,
  });
  invalidateTransmissionConfig(userId);
  return Response.json({ connection, rpcVersion: result.rpcVersion ?? null });
}

/** `/_config` — GET the connection, PUT/POST to save it, DELETE to forget it. */
export async function handleConfigRoute(req: Request, userId: number, subpath: string): Promise<Response> {
  if (subpath && subpath !== '/') return bad('not found', 404);

  if (req.method === 'GET') return connectionState(userId);
  if (req.method === 'POST' || req.method === 'PUT') return save(req, userId);

  if (req.method === 'DELETE') {
    await deleteServiceConnection(userId, 'transmission');
    invalidateTransmissionConfig(userId);
    return connectionState(userId);
  }

  return bad('method not allowed', 405);
}
