import express from 'express';
import { authenticateToken } from '../middleware/auth.js';
import Team from '../models/Team.js';
import TeamMember from '../models/TeamMember.js';
import TeamSettings from '../models/TeamSettings.js';
import User from '../models/User.js';
import sequelize from '../config/database.js';

const router = express.Router();

/**
 * PHASE 3: Team Management Endpoints
 * 12 endpoints for complete team lifecycle management
 */

// 1. GET /api/teams - List user's teams
router.get('/', authenticateToken, async (req, res, next) => {
  try {
    const teams = await Team.findAll({
      include: [{
        model: TeamMember,
        where: { userId: req.user.id, isActive: true },
        attributes: ['role']
      }],
      order: [['createdAt', 'DESC']]
    });

    res.status(200).json({
      status: 'success',
      code: 'TEAMS_RETRIEVED',
      message: 'Teams retrieved successfully',
      data: { teams }
    });
  } catch (error) {
    next(error);
  }
});

// 2. POST /api/teams - Create team
router.post('/', authenticateToken, async (req, res, next) => {
  const transaction = await sequelize.transaction();
  try {
    const { name, description } = req.body;

    if (!name) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'Team name is required',
        data: null
      });
    }

    const team = await Team.create({
      name,
      description,
      ownerId: req.user.id
    }, { transaction });

    // Add creator as admin
    await TeamMember.create({
      teamId: team.id,
      userId: req.user.id,
      role: 'admin'
    }, { transaction });

    // Create default settings
    await TeamSettings.create({
      teamId: team.id
    }, { transaction });

    await transaction.commit();

    res.status(201).json({
      status: 'success',
      code: 'TEAM_CREATED',
      message: 'Team created successfully',
      data: { team }
    });
  } catch (error) {
    await transaction.rollback();
    next(error);
  }
});

// 3. GET /api/teams/:id - Get team details
router.get('/:id', authenticateToken, async (req, res, next) => {
  try {
    const team = await Team.findOne({
      where: { id: req.params.id },
      include: [{
        model: TeamMember,
        where: { userId: req.user.id, isActive: true },
        attributes: ['role']
      }]
    });

    if (!team) {
      return res.status(404).json({
        status: 'error',
        code: 'TEAM_NOT_FOUND',
        message: 'Team not found',
        data: null
      });
    }

    res.status(200).json({
      status: 'success',
      code: 'TEAM_RETRIEVED',
      message: 'Team retrieved successfully',
      data: { team }
    });
  } catch (error) {
    next(error);
  }
});

// 4. PUT /api/teams/:id - Update team
router.put('/:id', authenticateToken, async (req, res, next) => {
  try {
    const team = await Team.findOne({
      where: { id: req.params.id },
      include: [{
        model: TeamMember,
        where: { userId: req.user.id, role: 'admin' }
      }]
    });

    if (!team) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'Only team admins can update team',
        data: null
      });
    }

    const { name, description } = req.body;
    await team.update({ name, description });

    res.status(200).json({
      status: 'success',
      code: 'TEAM_UPDATED',
      message: 'Team updated successfully',
      data: { team }
    });
  } catch (error) {
    next(error);
  }
});

// 5. DELETE /api/teams/:id - Delete team (admin only)
router.delete('/:id', authenticateToken, async (req, res, next) => {
  const transaction = await sequelize.transaction();
  try {
    const team = await Team.findOne({
      where: { id: req.params.id, ownerId: req.user.id }
    });

    if (!team) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'Only team owner can delete team',
        data: null
      });
    }

    await TeamMember.destroy({
      where: { teamId: team.id },
      transaction
    });

    await TeamSettings.destroy({
      where: { teamId: team.id },
      transaction
    });

    await team.destroy({ transaction });
    await transaction.commit();

    res.status(200).json({
      status: 'success',
      code: 'TEAM_DELETED',
      message: 'Team deleted successfully',
      data: null
    });
  } catch (error) {
    await transaction.rollback();
    next(error);
  }
});

// 6. GET /api/teams/:id/members - List team members
router.get('/:id/members', authenticateToken, async (req, res, next) => {
  try {
    const team = await Team.findOne({
      where: { id: req.params.id },
      include: [{
        model: TeamMember,
        where: { userId: req.user.id }
      }]
    });

    if (!team) {
      return res.status(404).json({
        status: 'error',
        code: 'TEAM_NOT_FOUND',
        message: 'Team not found',
        data: null
      });
    }

    const members = await TeamMember.findAll({
      where: { teamId: req.params.id, isActive: true },
      include: [{
        model: User,
        attributes: ['id', 'name', 'email', 'role']
      }]
    });

    res.status(200).json({
      status: 'success',
      code: 'TEAM_MEMBERS_RETRIEVED',
      message: 'Team members retrieved successfully',
      data: { members }
    });
  } catch (error) {
    next(error);
  }
});

// 7. POST /api/teams/:id/members - Add team member
router.post('/:id/members', authenticateToken, async (req, res, next) => {
  try {
    const { userId, role = 'viewer' } = req.body;

    // Check user is team admin
    const admin = await TeamMember.findOne({
      where: { teamId: req.params.id, userId: req.user.id, role: 'admin' }
    });

    if (!admin) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'Only team admins can add members',
        data: null
      });
    }

    const member = await TeamMember.create({
      teamId: req.params.id,
      userId,
      role,
      invitedBy: req.user.id
    });

    res.status(201).json({
      status: 'success',
      code: 'MEMBER_ADDED',
      message: 'Member added to team',
      data: { member }
    });
  } catch (error) {
    next(error);
  }
});

// 8. PUT /api/teams/:id/members/:memberId - Update member role
router.put('/:id/members/:memberId', authenticateToken, async (req, res, next) => {
  try {
    const { role } = req.body;

    // Check user is team admin
    const admin = await TeamMember.findOne({
      where: { teamId: req.params.id, userId: req.user.id, role: 'admin' }
    });

    if (!admin) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'Only team admins can manage members',
        data: null
      });
    }

    const member = await TeamMember.findOne({
      where: { id: req.params.memberId, teamId: req.params.id }
    });

    if (!member) {
      return res.status(404).json({
        status: 'error',
        code: 'MEMBER_NOT_FOUND',
        message: 'Team member not found',
        data: null
      });
    }

    await member.update({ role });

    res.status(200).json({
      status: 'success',
      code: 'MEMBER_UPDATED',
      message: 'Member role updated',
      data: { member }
    });
  } catch (error) {
    next(error);
  }
});

// 9. DELETE /api/teams/:id/members/:memberId - Remove member
router.delete('/:id/members/:memberId', authenticateToken, async (req, res, next) => {
  try {
    // Check user is team admin
    const admin = await TeamMember.findOne({
      where: { teamId: req.params.id, userId: req.user.id, role: 'admin' }
    });

    if (!admin) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'Only team admins can remove members',
        data: null
      });
    }

    const member = await TeamMember.findOne({
      where: { id: req.params.memberId, teamId: req.params.id }
    });

    if (!member) {
      return res.status(404).json({
        status: 'error',
        code: 'MEMBER_NOT_FOUND',
        message: 'Team member not found',
        data: null
      });
    }

    await member.update({ isActive: false });

    res.status(200).json({
      status: 'success',
      code: 'MEMBER_REMOVED',
      message: 'Member removed from team',
      data: null
    });
  } catch (error) {
    next(error);
  }
});

// 10. GET /api/teams/:id/settings - Get team settings
router.get('/:id/settings', authenticateToken, async (req, res, next) => {
  try {
    const member = await TeamMember.findOne({
      where: { teamId: req.params.id, userId: req.user.id, isActive: true }
    });

    if (!member) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'Not a team member',
        data: null
      });
    }

    const settings = await TeamSettings.findOne({
      where: { teamId: req.params.id }
    });

    res.status(200).json({
      status: 'success',
      code: 'TEAM_SETTINGS_RETRIEVED',
      message: 'Team settings retrieved',
      data: { settings }
    });
  } catch (error) {
    next(error);
  }
});

// 11. PUT /api/teams/:id/settings - Update team settings
router.put('/:id/settings', authenticateToken, async (req, res, next) => {
  try {
    const admin = await TeamMember.findOne({
      where: { teamId: req.params.id, userId: req.user.id, role: 'admin' }
    });

    if (!admin) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'Only team admins can update settings',
        data: null
      });
    }

    const settings = await TeamSettings.findOne({
      where: { teamId: req.params.id }
    });

    await settings.update(req.body);

    res.status(200).json({
      status: 'success',
      code: 'TEAM_SETTINGS_UPDATED',
      message: 'Team settings updated',
      data: { settings }
    });
  } catch (error) {
    next(error);
  }
});

// 12. GET /api/teams/:id/dashboard - Get team dashboard analytics
router.get('/:id/dashboard', authenticateToken, async (req, res, next) => {
  try {
    const member = await TeamMember.findOne({
      where: { teamId: req.params.id, userId: req.user.id, isActive: true }
    });

    if (!member) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'Not a team member',
        data: null
      });
    }

    // Aggregate team statistics
    const memberCount = await TeamMember.count({
      where: { teamId: req.params.id, isActive: true }
    });

    const dashboard = {
      teamId: req.params.id,
      memberCount,
      activeMembers: memberCount,
      recentActivity: [],
      stats: {
        projectsCreatedThisMonth: 0,
        componentsCreatedThisMonth: 0,
        tokensUpdatedThisMonth: 0
      }
    };

    res.status(200).json({
      status: 'success',
      code: 'TEAM_DASHBOARD_RETRIEVED',
      message: 'Team dashboard retrieved',
      data: { dashboard }
    });
  } catch (error) {
    next(error);
  }
});

export default router;
