const express = require('express');
const router = express.Router();
const nocodbService = require('../services/nocodb');
const config = require('../config');
const logger = require('../utils/logger');
const { generateQRCode } = require('../services/qrcode');

// Debug session endpoint
router.get('/session', (req, res) => {
    res.json({
        sessionID: req.sessionID,
        session: req.session,
        cookies: req.cookies,
        authenticated: req.session?.authenticated || false
    });
});

// Check table structure
router.get('/table-structure', async (req, res) => {
    try {
        const response = await nocodbService.getAll(config.nocodb.tableId, {
            limit: 1
        });
        
        const sample = response.list?.[0] || {};
        
        res.json({
            success: true,
            fields: Object.keys(sample),
            sampleRecord: sample,
            idField: sample.ID ? 'ID' : (sample.Id ? 'Id' : (sample.id ? 'id' : 'unknown'))
        });
        
    } catch (error) {
        logger.error('Error checking table structure:', error);
        res.status(500).json({
            success: false,
            error: 'Failed to check table structure'
        });
    }
});

// QR code generation test
router.get('/test-qr', async (req, res) => {
    try {
        const testUrl = req.query.url || 'https://example.com/test';
        const testSize = parseInt(req.query.size) || 200;
        
        logger.info('Testing local QR code generation...');
        
        const qrOptions = {
            type: 'png',
            width: testSize,
            margin: 1,
            color: {
                dark: '#000000',
                light: '#FFFFFF'
            },
            errorCorrectionLevel: 'M'
        };
        
        const buffer = await generateQRCode(testUrl, qrOptions);
        
        res.set({
            'Content-Type': 'image/png',
            'Content-Length': buffer.length
        });
        
        res.send(buffer);
        
    } catch (error) {
        logger.error('QR code test failed:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

// Walk sheet configuration debug
router.get('/walk-sheet-config', async (req, res) => {
    try {
        const debugInfo = {
            settingsSheetId: config.nocodb.settingsSheetId,
            settingsSheetConfigured: process.env.NOCODB_SETTINGS_SHEET,
            hasSettingsSheet: !!config.nocodb.settingsSheetId,
            timestamp: new Date().toISOString()
        };

        if (!config.nocodb.settingsSheetId) {
            return res.json({
                success: true,
                debug: debugInfo,
                message: 'Settings sheet not configured'
            });
        }

        // Test connection to settings sheet
        const response = await nocodbService.getAll(config.nocodb.settingsSheetId, {
            limit: 5,
            sort: '-created_at'
        });

        const records = response.list || [];
        const sampleRecord = records[0] || {};

        res.json({
            success: true,
            debug: {
                ...debugInfo,
                connectionTest: 'success',
                recordCount: records.length,
                availableFields: Object.keys(sampleRecord),
                sampleRecord: sampleRecord,
                recentRecords: records.slice(0, 3).map(r => ({
                    id: r.id || r.Id || r.ID,
                    created_at: r.created_at,
                    walk_sheet_title: r.walk_sheet_title,
                    hasQrCodes: !!(r.qr_code_1_url || r.qr_code_2_url || r.qr_code_3_url)
                }))
            }
        });

    } catch (error) {
        logger.error('Error debugging walk sheet config:', error);
        res.json({
            success: false,
            debug: {
                settingsSheetId: config.nocodb.settingsSheetId,
                settingsSheetConfigured: process.env.NOCODB_SETTINGS_SHEET,
                hasSettingsSheet: !!config.nocodb.settingsSheetId,
                timestamp: new Date().toISOString(),
                error: error.message,
                errorDetails: error.response?.data
            }
        });
    }
});

// Test walk sheet save
router.post('/test-walk-sheet-save', async (req, res) => {
    try {
        const testConfig = {
            walk_sheet_title: 'Test Walk Sheet',
            walk_sheet_subtitle: 'Test Subtitle',
            walk_sheet_footer: 'Test Footer',
            qr_code_1_url: 'https://example.com/test1',
            qr_code_1_label: 'Test QR 1',
            qr_code_2_url: 'https://example.com/test2',
            qr_code_2_label: 'Test QR 2',
            qr_code_3_url: 'https://example.com/test3',
            qr_code_3_label: 'Test QR 3'
        };

        logger.info('Testing walk sheet configuration save...');

        if (!config.nocodb.settingsSheetId) {
            return res.json({
                success: false,
                test: 'failed',
                error: 'Settings sheet not configured',
                config: testConfig
            });
        }

        const walkSheetData = {
            created_at: new Date().toISOString(),
            created_by: req.session.userEmail,
            ...testConfig
        };

        const response = await nocodbService.create(
            config.nocodb.settingsSheetId,
            walkSheetData
        );

        res.json({
            success: true,
            test: 'passed',
            message: 'Test walk sheet configuration saved successfully',
            testData: walkSheetData,
            saveResponse: response,
            settingsId: response.id || response.Id || response.ID
        });

    } catch (error) {
        logger.error('Test walk sheet save failed:', error);
        res.json({
            success: false,
            test: 'failed',
            error: error.message,
            errorDetails: error.response?.data,
            timestamp: new Date().toISOString()
        });
    }
});

// Raw walk sheet data
router.get('/walk-sheet-raw', async (req, res) => {
    try {
        if (!config.nocodb.settingsSheetId) {
            return res.json({ error: 'No settings sheet ID configured' });
        }

        const response = await nocodbService.getAll(config.nocodb.settingsSheetId, {
            sort: '-created_at',
            limit: 5
        });

        return res.json({
            success: true,
            tableId: config.nocodb.settingsSheetId,
            records: response.list || [],
            count: response.list?.length || 0
        });
    } catch (error) {
        logger.error('Error fetching raw walk sheet data:', error);
        return res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

// Add this route to check login table structure
router.get('/login-structure', async (req, res) => {
    try {
        const loginSheetId = config.nocodb.loginSheetId;
        
        if (!loginSheetId) {
            return res.status(400).json({
                success: false,
                error: 'Login sheet ID not configured'
            });
        }
        
        // Get table structure
        const tableId = extractTableId(loginSheetId);
        const response = await nocodbService.api.get(`/db/meta/tables/${tableId}`);
        
        const columns = response.data.columns.map(col => ({
            column_name: col.column_name,
            title: col.title,
            uidt: col.uidt,
            required: col.rqd
        }));
        
        res.json({
            success: true,
            tableId,
            columns,
            columnNames: columns.map(c => c.column_name)
        });
        
    } catch (error) {
        logger.error('Error fetching login table structure:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

module.exports = router;