import { sql } from "@/lib/db";
import { signJwt } from "@/lib/jwt";

export type UserProfile = {
  id: string;
  name: string;
  email: string;
  role: string | null;
};

type UserRow = {
  id: string;
  name: string;
  email: string;
  role: string | null;
};

export const toProfile = (row: UserRow): UserProfile => ({
  id: row.id,
  name: row.name,
  email: row.email,
  role: row.role,
});

export const issueSession = (
  row: UserRow,
  expiresInSeconds?: number,
): { token: string; user: UserProfile } => ({
  token: signJwt({ sub: row.id, email: row.email }, expiresInSeconds),
  user: toProfile(row),
});

export const findUserByEmail = async (
  email: string,
): Promise<UserRow | null> => {
  const rows = await sql<UserRow>`
    SELECT id, name, email, role FROM users WHERE email = ${email}
  `;
  return rows[0] ?? null;
};
