import { setCookie, deleteCookie } from 'hono/cookie';
import type { Context } from 'hono';
import type { ApiEnvelope, CurrentUser, Env, SiteSettings } from '../env';
import { mediaUrl } from '../utils/image';
import { sessionCookieName } from '../middleware/session';

export function apiOk<T>(c: Context<Env>, data: T, status = 200): Response {
  return c.json<ApiEnvelope<T>>({ success: true, data }, status as never);
}

export function apiFail(c: Context<Env>, message: string, status = 400, code = 'BAD_REQUEST'): Response {
  return c.json<ApiEnvelope>({ success: false, message, code }, status as never);
}

export function setSessionCookie(c: Context<Env>, token: string, maxAge: number): void {
  setCookie(c, sessionCookieName(c.env), token, {
    path: '/',
    httpOnly: true,
    sameSite: 'Lax',
    secure: new URL(c.req.url).protocol === 'https:',
    maxAge
  });
}

export function clearSessionCookie(c: Context<Env>): void {
  deleteCookie(c, sessionCookieName(c.env), { path: '/' });
}

export function publicUser(user: CurrentUser, settings: SiteSettings) {
  return {
    id: user.id,
    username: user.username,
    email: user.email,
    displayName: user.displayName,
    avatarUrl: mediaUrl(settings.cdn_base_url, user.avatarKey),
    bio: user.bio,
    url: user.url,
    role: user.role
  };
}
