import {eq} from "drizzle-orm";
import {getDb} from "../../../db";
import {users} from "../../../db/schema";
import {clearSessionCookie,createSession,deleteSession,getFleetUser,sessionCookie,verifyPassword} from "../../../lib/fleet-auth";
export async function GET(request:Request){const s=await getFleetUser(request);return s?Response.json({profile:s.profile}):Response.json({error:"نشست معتبر نیست"},{status:401})}
export async function POST(request:Request){const b:any=await request.json().catch(()=>({}));if(b.action==="logout"){await deleteSession(request);const r=Response.json({ok:true});r.headers.append("Set-Cookie",clearSessionCookie());return r}const username=String(b.username||"").trim().toLowerCase(),password=String(b.password||"");if(!/^[a-z0-9._-]{3,32}$/.test(username)||password.length<8)return Response.json({error:"نام کاربری یا رمز عبور صحیح نیست."},{status:400});const [u]=await getDb().select().from(users).where(eq(users.username,username)).limit(1);if(!u?.isActive||!await verifyPassword(password,u.passwordHash))return Response.json({error:"نام کاربری یا رمز عبور صحیح نیست."},{status:401});const s=await createSession(u.id),r=Response.json({profile:{id:u.id,username:u.username,full_name:u.fullName,role:u.role,driver_id:u.driverId,is_active:u.isActive,must_change_password:u.mustChangePassword}});r.headers.append("Set-Cookie",sessionCookie(s.token));return r}
