import { Router, Request, Response } from 'express';
import { supabaseAdmin } from '../config/supabase';
import { db } from '../database/connection';
import { users } from '../database/schema';
import { eq } from 'drizzle-orm';
import { authenticateUser, AuthenticatedRequest } from '../middleware/auth';

const router = Router();

// Creates both the Supabase Auth user and the matching row in public.users (same UUID).
router.post('/register', async (req: Request, res: Response) => {
  try {
    const { email, password, fullName, role = 'user' } = req.body;

    if (!email || !password || !fullName) {
      return res.status(400).json({ error: 'Email, password, and full name are required' });
    }

    // Create user in Supabase Auth
    const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({
      email,
      password,
      user_metadata: {
        full_name: fullName,
        role: role
      },
      email_confirm: true // Auto-confirm email for development
    });

    if (authError) {
      console.error('Supabase auth error:', authError);
      return res.status(400).json({ error: authError.message });
    }

    if (!authData.user) {
      return res.status(400).json({ error: 'Failed to create user' });
    }

    // Create user record in our database
    try {
      await db.insert(users).values({
        id: authData.user.id,
        email: authData.user.email!,
        fullName,
        role
      });
    } catch (dbError: any) {
      console.error('Database error:', dbError);
      // If user already exists, try to update instead
      if (dbError.code === '23505') { // Unique violation
        try {
          await db.update(users)
            .set({ fullName, role, updatedAt: new Date() })
            .where(eq(users.id, authData.user.id));
        } catch (updateError) {
          console.error('Update error:', updateError);
          return res.status(500).json({ error: 'Failed to create or update user record' });
        }
      } else {
        return res.status(500).json({ error: 'Failed to create user record' });
      }
    }

    return res.status(201).json({
      message: 'User created successfully',
      user: {
        id: authData.user.id,
        email: authData.user.email,
        fullName,
        role
      }
    });
  } catch (error) {
    console.error('Registration error:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

// Optional: app mostly signs in via Supabase in the browser; this still returns tokens if you call it from a client.
router.post('/login', async (req: Request, res: Response) => {
  try {
    const { email, password } = req.body;

    if (!email || !password) {
      return res.status(400).json({ error: 'Email and password are required' });
    }

    // Authenticate with Supabase
    const { data, error } = await supabaseAdmin.auth.signInWithPassword({
      email,
      password
    });

    if (error) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    if (!data.user || !data.session) {
      return res.status(401).json({ error: 'Authentication failed' });
    }

    // Get user details from our database
    const userDetails = await db
      .select()
      .from(users)
      .where(eq(users.id, data.user.id))
      .limit(1);

    const user = userDetails[0];

    return res.json({
      message: 'Login successful',
      user: {
        id: data.user.id,
        email: data.user.email,
        fullName: user?.fullName,
        role: user?.role || 'user'
      },
      session: {
        access_token: data.session.access_token,
        refresh_token: data.session.refresh_token,
        expires_at: data.session.expires_at
      }
    });
  } catch (error) {
    console.error('Login error:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

// Get current user
router.get('/me', authenticateUser, async (req: Request, res: Response) => {
  try {
    const userDetails = await db
      .select()
      .from(users)
      .where(eq(users.id, req.user!.id))
      .limit(1);

    const user = userDetails[0];

    return res.json({
      user: {
        id: req.user!.id,
        email: req.user!.email,
        fullName: user?.fullName,
        role: user?.role || 'user'
      }
    });
  } catch (error) {
    console.error('Get user error:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

// Logout endpoint
router.post('/logout', authenticateUser, async (req: Request, res: Response) => {
  try {
    const authHeader = req.headers.authorization;
    const token = authHeader?.split(' ')[1];

    if (token) {
      await supabaseAdmin.auth.admin.signOut(token);
    }

    return res.json({ message: 'Logout successful' });
  } catch (error) {
    console.error('Logout error:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

export default router;
