import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';
import crypto from 'crypto';
import { checkAdmin } from '@/lib/admin-auth';

const MAX_BANNER_SIZE = 2 * 1024 * 1024; // 2 MB
const ALLOWED_BANNER_TYPES = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp'];

// GET - public: return active banner
export async function GET() {
  try {
    console.log('[BANNER] Fetching active banner');
    const banner = await db.banner.findFirst({
      where: { active: true },
    });

    if (!banner) {
      console.log('[BANNER] No active banner found');
      return Response.json({ banner: null });
    }

    console.log('[BANNER] Active banner found:', banner.id, 'type:', banner.adType);
    return Response.json({
      banner: {
        id: banner.id,
        adType: banner.adType,
        imageUrl: banner.imageUrl,
        adCode: banner.adCode,
        linkUrl: banner.linkUrl,
        text: banner.text,
        active: banner.active,
        position: banner.position,
      },
    });
  } catch (error: unknown) {
    console.error('[BANNER] GET error:', error);
    const message = error instanceof Error ? error.message : 'خطأ في جلب البانر';
    return Response.json({ error: message }, { status: 500 });
  }
}

// PUT - admin: update or create banner
export async function PUT(request: NextRequest) {
  const auth = await checkAdmin(request);
  if (!auth.authorized) {
    return Response.json({ error: auth.error }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { adType, imageUrl, adCode, linkUrl, text, active, position } = body;

    console.log('[BANNER] Upserting banner:', { adType, hasImage: !!imageUrl, hasCode: !!adCode, active, position });

    const banner = await db.banner.upsert({
      where: {
        id: (
          await db.banner.findFirst({
            select: { id: true },
          })
        )?.id || '__placeholder__',
      },
      update: {
        ...(adType !== undefined && { adType }),
        ...(imageUrl !== undefined && { imageUrl }),
        ...(adCode !== undefined && { adCode }),
        ...(linkUrl !== undefined && { linkUrl }),
        ...(text !== undefined && { text }),
        ...(active !== undefined && { active }),
        ...(position !== undefined && { position }),
      },
      create: {
        adType: adType || 'image',
        imageUrl: imageUrl || '',
        adCode: adCode || '',
        linkUrl: linkUrl || '',
        text: text || '',
        active: active ?? false,
        position: position || 'top',
      },
    });

    console.log('[BANNER] Banner upserted:', banner.id);
    return Response.json(banner);
  } catch (error: unknown) {
    console.error('[BANNER] PUT error:', error);
    const message = error instanceof Error ? error.message : 'خطأ في تحديث البانر';
    return Response.json({ error: message }, { status: 500 });
  }
}

// POST - upload banner image (admin only)
export async function POST(request: NextRequest) {
  const auth = await checkAdmin(request);
  if (!auth.authorized) {
    return Response.json({ error: auth.error }, { status: 401 });
  }

  try {
    const formData = await request.formData();
    const file = formData.get('image') as File | null;

    if (!file) {
      return Response.json({ error: 'لم يتم إرسال صورة' }, { status: 400 });
    }

    if (!ALLOWED_BANNER_TYPES.includes(file.type)) {
      return Response.json(
        { error: 'نوع الملف غير مدعوم. استخدم PNG أو JPG أو WEBP' },
        { status: 400 },
      );
    }

    if (file.size > MAX_BANNER_SIZE) {
      return Response.json(
        { error: 'حجم الصورة كبير جداً. الحد الأقصى 2 ميجا' },
        { status: 400 },
      );
    }

    const buffer = Buffer.from(await file.arrayBuffer());
    console.log('[BANNER] Image received:', file.name, 'size:', buffer.length, 'bytes', 'type:', file.type);

    const bannerDir = path.join(process.cwd(), 'public', 'banners');
    await mkdir(bannerDir, { recursive: true });

    const ext = file.type === 'image/png' ? 'png' : file.type === 'image/webp' ? 'webp' : 'jpg';
    const filename = `banner_${crypto.randomBytes(8).toString('hex')}.${ext}`;
    await writeFile(path.join(bannerDir, filename), buffer);

    const imageUrl = `/banners/${filename}`;
    console.log('[BANNER] Image saved:', imageUrl);

    return Response.json({ success: true, imageUrl });
  } catch (error: unknown) {
    console.error('[BANNER] POST error:', error);
    const message = error instanceof Error ? error.message : 'خطأ في رفع صورة البانر';
    return Response.json({ error: message }, { status: 500 });
  }
}