import {createHash,randomBytes,scrypt as scryptCallback,timingSafeEqual} from "node:crypto";
import {promisify} from "node:util";
import {and,eq,gt} from "drizzle-orm";
import {getDb} from "../db";
import {sessions,users} from "../db/schema";
const scrypt=promisify(scryptCallback);
export type FleetRole="general_manager"|"supervisor"|"driver";
export type FleetProfile={id:string;username:string;full_name:string;role:FleetRole;driver_id:number|null;is_active:boolean;must_change_password:boolean};
const cookie=(r:Request,n:string)=>r.headers.get("cookie")?.split(";").map(v=>v.trim()).find(v=>v.startsWith(n+"="))?.slice(n.length+1)||"";
const tokenHash=(v:string)=>createHash("sha256").update(v).digest("hex");
export async function hashPassword(password:string){const salt=randomBytes(16).toString("hex"),key=await scrypt(password,salt,64) as Buffer;return `scrypt:${salt}:${key.toString("hex")}`}
export async function verifyPassword(password:string,stored:string){const [,salt,want]=stored.split(":");if(!salt||!want)return false;const got=await scrypt(password,salt,64) as Buffer,w=Buffer.from(want,"hex");return got.length===w.length&&timingSafeEqual(got,w)}
export async function createSession(userId:string){const token=randomBytes(32).toString("base64url"),expiresAt=new Date(Date.now()+30*864e5).toISOString();await getDb().insert(sessions).values({tokenHash:tokenHash(token),userId,expiresAt});return {token}}
export async function getFleetUser(request:Request){const token=cookie(request,"fleet_session");if(!token)return null;const [row]=await getDb().select({id:users.id,username:users.username,fullName:users.fullName,role:users.role,driverId:users.driverId,isActive:users.isActive,mustChangePassword:users.mustChangePassword}).from(sessions).innerJoin(users,eq(sessions.userId,users.id)).where(and(eq(sessions.tokenHash,tokenHash(token)),gt(sessions.expiresAt,new Date().toISOString()))).limit(1);if(!row?.isActive)return null;const profile:FleetProfile={id:row.id,username:row.username,full_name:row.fullName,role:row.role as FleetRole,driver_id:row.driverId,is_active:row.isActive,must_change_password:row.mustChangePassword};return {token,profile}}
export async function deleteSession(request:Request){const token=cookie(request,"fleet_session");if(token)await getDb().delete(sessions).where(eq(sessions.tokenHash,tokenHash(token)))}
const secure=()=>process.env.COOKIE_SECURE==="0"?"":"; Secure";
export const sessionCookie=(token:string)=>`fleet_session=${token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=2592000${secure()}`;
export const clearSessionCookie=()=>`fleet_session=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0${secure()}`;
