import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';
import type { Partner } from '@/types/data';

const DATA_DIR = join(process.cwd(), 'data');
const PARTNERS_FILE = join(DATA_DIR, 'partners.json');

// Ensure data directory exists
function ensureDataDir() {
  if (!existsSync(DATA_DIR)) {
    mkdirSync(DATA_DIR, { recursive: true });
  }
}

async function checkAuth() {
  const cookieStore = await cookies();
  const auth = cookieStore.get('admin-auth');
  return auth?.value === 'authenticated';
}

export async function POST(request: NextRequest) {
  if (!(await checkAuth())) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    ensureDataDir();
    const { partners }: { partners: Partner[] } = await request.json();
    
    // Clean up any order fields that might have been added, keep only display field
    const cleanedPartners = partners.map((partner: any) => {
      const { order, ...rest } = partner;
      return rest as Partner;
    });
    
    writeFileSync(PARTNERS_FILE, JSON.stringify(cleanedPartners, null, 2));
    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to reorder partners' },
      { status: 500 }
    );
  }
}

