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 { SiteInfo } from '@/types/data';

const DATA_DIR = join(process.cwd(), 'data');
const SITEINFO_FILE = join(DATA_DIR, 'siteinfo.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(SITEINFO_FILE)) {
      return NextResponse.json(
        { error: 'Siteinfo file not found' },
        { 
          status: 404,
          headers: {
            'Cache-Control': 'no-store, no-cache, must-revalidate, private',
          },
        }
      );
    }
    const data = readFileSync(SITEINFO_FILE, 'utf-8');
    const siteInfo = JSON.parse(data);
    return NextResponse.json(siteInfo, {
      headers: {
        'Cache-Control': 'private, no-cache, no-store, must-revalidate',
      },
    });
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to read siteinfo' },
      { 
        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 { siteInfo, oldSiteLogo, oldFavicon }: { 
      siteInfo: SiteInfo; 
      oldSiteLogo?: string; 
      oldFavicon?: string;
    } = await request.json();
    
    // Read current siteinfo to compare (if exists)
    let currentSiteInfo: SiteInfo | null = null;
    if (existsSync(SITEINFO_FILE)) {
      const currentData = readFileSync(SITEINFO_FILE, 'utf-8');
      currentSiteInfo = JSON.parse(currentData);
    }
    
    // Delete old site logo if changed
    if (oldSiteLogo && oldSiteLogo !== siteInfo.siteLogo && oldSiteLogo.startsWith('/')) {
      try {
        const oldLogoPath = join(process.cwd(), 'public', oldSiteLogo.replace(/^\//, ''));
        if (existsSync(oldLogoPath) && !oldLogoPath.includes('logo.png')) {
          // Don't delete default logo.png
          await unlink(oldLogoPath);
        }
      } catch (error) {
        console.log('Could not delete old site logo:', error);
      }
    }
    
    // Delete old favicon if changed
    if (oldFavicon && oldFavicon !== siteInfo.favicon && oldFavicon.startsWith('/')) {
      try {
        const oldFaviconPath = join(process.cwd(), 'public', oldFavicon.replace(/^\//, ''));
        if (existsSync(oldFaviconPath)) {
          await unlink(oldFaviconPath);
        }
      } catch (error) {
        console.log('Could not delete old favicon:', error);
      }
    }
    
    ensureDataDir();
    writeFileSync(SITEINFO_FILE, JSON.stringify(siteInfo, null, 2));
    return NextResponse.json(
      { success: true, siteInfo },
      {
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to update siteinfo' },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

