import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { unlink } from 'fs/promises';
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 GET() {
  if (!(await checkAuth())) {
    return NextResponse.json(
      { error: 'Unauthorized' },
      { 
        status: 401,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }

  try {
    ensureDataDir();
    if (!existsSync(PARTNERS_FILE)) {
      return NextResponse.json([], {
        headers: {
          'Cache-Control': 'private, no-cache, no-store, must-revalidate',
        },
      });
    }
    const data = readFileSync(PARTNERS_FILE, 'utf-8');
    const partners = JSON.parse(data);
    return NextResponse.json(partners, {
      headers: {
        'Cache-Control': 'private, no-cache, no-store, must-revalidate',
      },
    });
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to read partners' },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

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

  try {
    ensureDataDir();
    const partner: Partner = await request.json();
    
    let partners: Partner[] = [];
    if (existsSync(PARTNERS_FILE)) {
      const data = readFileSync(PARTNERS_FILE, 'utf-8');
      partners = JSON.parse(data);
    }
    
    partners.push(partner);
    writeFileSync(PARTNERS_FILE, JSON.stringify(partners, null, 2));
    return NextResponse.json(
      { success: true, partner },
      {
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to add partner' },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

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

  try {
    ensureDataDir();
    const { index, partner, oldLogo }: { index: number; partner: Partner; oldLogo?: string } =
      await request.json();
    
    if (!existsSync(PARTNERS_FILE)) {
      return NextResponse.json({ error: 'Partners file not found' }, { status: 404 });
    }
    
    const data = readFileSync(PARTNERS_FILE, 'utf-8');
    const partners: Partner[] = JSON.parse(data);
    
    // Delete old logo if logo changed and old logo exists
    if (oldLogo && oldLogo !== partner.logo && oldLogo.startsWith('/')) {
      try {
        const oldLogoPath = join(process.cwd(), 'public', oldLogo.replace(/^\//, ''));
        if (existsSync(oldLogoPath)) {
          await unlink(oldLogoPath);
        }
      } catch (error) {
        // Ignore errors when deleting old logo
        console.log('Could not delete old partner logo:', error);
      }
    }
    
    partners[index] = partner;
    writeFileSync(PARTNERS_FILE, JSON.stringify(partners, null, 2));
    return NextResponse.json(
      { success: true },
      {
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to update partner' },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

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

  try {
    ensureDataDir();
    const { index }: { index: number } = await request.json();
    
    if (!existsSync(PARTNERS_FILE)) {
      return NextResponse.json({ error: 'Partners file not found' }, { status: 404 });
    }
    
    const data = readFileSync(PARTNERS_FILE, 'utf-8');
    const partners: Partner[] = JSON.parse(data);
    const deletedPartner = partners[index];
    
    // Delete partner logo file
    if (deletedPartner.logo && deletedPartner.logo.startsWith('/')) {
      try {
        const logoPath = join(process.cwd(), 'public', deletedPartner.logo.replace(/^\//, ''));
        if (existsSync(logoPath)) {
          await unlink(logoPath);
        }
      } catch (error) {
        // Ignore errors when deleting logo
        console.log('Could not delete partner logo:', error);
      }
    }
    
    partners.splice(index, 1);
    writeFileSync(PARTNERS_FILE, JSON.stringify(partners, null, 2));
    return NextResponse.json(
      { success: true },
      {
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to delete partner' },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

