import { SignJWT, jwtVerify } from 'jose';
import { cookies } from 'next/headers';
import pool from './db';

const JWT_SECRET = new TextEncoder().encode(
  process.env.JWT_SECRET || 'credispo-demo-secret-key-2026'
);

const COOKIE_NAME = 'credispo-session';

export interface SessionUser {
  id: string;
  email: string;
  role: string;
  name: string;
  company?: string;
}

export async function createToken(user: SessionUser): Promise<string> {
  return new SignJWT({ sub: user.id, email: user.email, role: user.role, name: user.name, company: user.company })
    .setProtectedHeader({ alg: 'HS256' })
    .setExpirationTime('7d')
    .setIssuedAt()
    .sign(JWT_SECRET);
}

export async function verifyToken(token: string): Promise<SessionUser | null> {
  try {
    const { payload } = await jwtVerify(token, JWT_SECRET);
    return {
      id: payload.sub as string,
      email: payload.email as string,
      role: payload.role as string,
      name: payload.name as string,
      company: payload.company as string | undefined,
    };
  } catch {
    return null;
  }
}

export async function getSessionUser(): Promise<SessionUser | null> {
  const cookieStore = cookies();
  const token = cookieStore.get(COOKIE_NAME)?.value;
  if (!token) return null;
  return verifyToken(token);
}

export async function getUserFromDB(userId: string) {
  const result = await pool.query(
    'SELECT id, email, role, name, company, phone, avatar_url, created_at, updated_at FROM users WHERE id = $1',
    [userId]
  );
  return result.rows[0] || null;
}

export { COOKIE_NAME };
