// app/api/auth/refresh/route.ts
import { NextRequest, NextResponse } from 'next/server';
import jwt from 'jsonwebtoken';
import pool from '../../../../lib/db/db';
import { RowDataPacket } from 'mysql2';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, x-api-key',
  'Access-Control-Allow-Credentials': 'true',
};

export async function OPTIONS() {
  return new NextResponse(null, {
    status: 204,
    headers: corsHeaders,
  });
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { refreshToken } = body;
    
    // Check API key
    const apiKey = req.headers.get("authorization");
    if (apiKey !== process.env.APP_API_KEY) {
      return NextResponse.json(
        { success: false, message: 'Unauthorized Access' },
        { status: 401, headers: corsHeaders }
      );
    }
    
    if (!refreshToken) {
      return NextResponse.json(
        { success: false, message: 'Refresh token required' },
        { status: 401, headers: corsHeaders }
      );
    }

    // Verify refresh token
    let decoded;
    try {
      decoded = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET as string) as any;
    } catch (error) {
      return NextResponse.json(
        { success: false, message: 'Invalid or expired refresh token' },
        { status: 401, headers: corsHeaders }
      );
    }

    // Get user from database
    const [users] = await pool.query<RowDataPacket[]>(
      "SELECT * FROM users WHERE id = ? AND refresh_token = ? AND is_active = 1",
      [decoded.id, refreshToken]
    );

    if (users.length === 0) {
      return NextResponse.json(
        { success: false, message: 'Invalid refresh token' },
        { status: 401, headers: corsHeaders }
      );
    }

    const user = users[0];
    const userData = {
      id: user.id,
      first_name: user.first_name,
      last_name: user.last_name,
      avatar: user.image,
      email: user.email,
      role: user.user_type
    };

    // Generate new access token
    const newAccessToken = jwt.sign(
      {
        id: user.id,
        first_name: user.first_name,
        last_name: user.last_name,
        avatar: user.image,
        email: user.email,
        role: user.user_type,
        type: 'access'
      },
      process.env.JWT_SECRET as string,
      { expiresIn: "15m" }
    );

    const response = NextResponse.json({
      success: true,
      token: newAccessToken,
      user: userData
    }, { headers: corsHeaders });

    // Update cookie
    response.cookies.set('app-token', newAccessToken, { 
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 15 * 60
    });

    return response;
  } catch (err: any) {
    console.error('Refresh token error:', err);
    return NextResponse.json(
      { success: false, message: 'Internal server error' },
      { status: 500, headers: corsHeaders }
    );
  }
}