import { queryWithRLS, queryOneWithRLS, getTransactionClient } from "../db.js";
async function createTeam(userId, name) {
  const user = await queryOneWithRLS(
    'SELECT id, email, name FROM "users" WHERE id = $1',
    [userId]
  );
  if (!user) {
    throw new Error("User not found");
  }
  const timestamp = Date.now().toString(36);
  const teamSlug = `team-${timestamp}-${userId.substring(0, 4).toLowerCase()}`;
  const teamName = name || (user.name ? `${user.name}'s Team` : "My Team");
  const tx = await getTransactionClient(userId);
  try {
    const [team] = await tx.query(
      `INSERT INTO "teams" (name, slug, "ownerId")
       VALUES ($1, $2, $3)
       RETURNING *`,
      [teamName, teamSlug, userId]
    );
    if (!team) {
      throw new Error("Failed to create team");
    }
    await tx.query(
      `INSERT INTO "team_members" ("teamId", "userId", role, "joinedAt")
       VALUES ($1, $2, 'owner', NOW())`,
      [team.id, userId]
    );
    const [freePlan] = await tx.query(
      `SELECT id FROM "plans" WHERE slug = 'free' LIMIT 1`
    );
    if (freePlan) {
      await tx.query(
        `INSERT INTO "subscriptions" ("teamId", "planId", status, "currentPeriodStart", "currentPeriodEnd", "billingInterval")
         VALUES ($1, $2, 'active', NOW(), NOW() + INTERVAL '100 years', 'monthly')`,
        [team.id, freePlan.id]
      );
    }
    await tx.commit();
    console.log(`Team created for user ${userId}: ${team.id}`);
    return team;
  } catch (error) {
    await tx.rollback();
    console.error(`Failed to create team for user ${userId}:`, error);
    throw error;
  }
}
async function getGlobalTeam() {
  const team = await queryOneWithRLS(
    `SELECT * FROM "teams"
     ORDER BY "createdAt" ASC
     LIMIT 1`,
    []
  );
  return team;
}
async function hasGlobalTeam() {
  const team = await getGlobalTeam();
  return team !== null;
}
async function addUserToGlobalTeam(userId, role = "member", invitedBy) {
  const team = await getGlobalTeam();
  if (!team) {
    throw new Error("No global team exists");
  }
  const existing = await queryOneWithRLS(
    'SELECT id FROM "team_members" WHERE "teamId" = $1 AND "userId" = $2',
    [team.id, userId]
  );
  if (existing) {
    console.log(`User ${userId} is already a member of team ${team.id}`);
    return;
  }
  await queryWithRLS(
    `INSERT INTO "team_members" ("teamId", "userId", role, "invitedBy", "joinedAt")
     VALUES ($1, $2, $3, $4, NOW())`,
    [team.id, userId, role, invitedBy || null],
    userId
  );
  console.log(`User ${userId} added to global team ${team.id} as ${role}`);
}
async function checkTeamPermission(userId, teamId, requiredRoles = ["owner", "admin"]) {
  const member = await queryOneWithRLS(
    'SELECT role FROM "team_members" WHERE "teamId" = $1 AND "userId" = $2',
    [teamId, userId],
    userId
  );
  if (!member) {
    return false;
  }
  return requiredRoles.includes(member.role);
}
async function getUserTeamRole(userId, teamId) {
  const member = await queryOneWithRLS(
    'SELECT role FROM "team_members" WHERE "teamId" = $1 AND "userId" = $2',
    [teamId, userId],
    userId
  );
  return (member == null ? void 0 : member.role) || null;
}
async function isTeamMember(userId, teamId) {
  const member = await queryOneWithRLS(
    'SELECT id FROM "team_members" WHERE "teamId" = $1 AND "userId" = $2',
    [teamId, userId],
    userId
  );
  return !!member;
}
async function getUserTeamsWithDetails(userId) {
  const teams = await queryWithRLS(
    `SELECT
      t.*,
      tm.role as "userRole",
      tm."joinedAt",
      COUNT(DISTINCT tm2.id) as "memberCount"
    FROM "teams" t
    INNER JOIN "team_members" tm ON t.id = tm."teamId"
    LEFT JOIN "team_members" tm2 ON t.id = tm2."teamId"
    WHERE tm."userId" = $1
    GROUP BY t.id, t.name, t.slug, t.description, t."ownerId", t."avatarUrl",
             t.settings, t."createdAt", t."updatedAt", tm.role, tm."joinedAt"
    ORDER BY
      tm.role = 'owner' DESC,  -- Teams owned by user first
      t."createdAt" DESC`,
    [userId],
    userId
  );
  return teams.map((team) => ({
    ...team,
    memberCount: parseInt(team.memberCount, 10)
  }));
}
async function getTeamWithMemberCount(teamId, userId) {
  const team = await queryOneWithRLS(
    `SELECT
      t.*,
      COUNT(DISTINCT tm.id) as "memberCount"
    FROM "teams" t
    LEFT JOIN "team_members" tm ON t.id = tm."teamId"
    WHERE t.id = $1
    GROUP BY t.id`,
    [teamId],
    userId
  );
  if (!team) {
    return null;
  }
  return {
    ...team,
    memberCount: parseInt(team.memberCount, 10)
  };
}
async function getTeamMembersWithUsers(teamId, userId) {
  const members = await queryWithRLS(
    `SELECT
      tm.*,
      u.name as "userName",
      u.email as "userEmail",
      u.image as "userImage"
    FROM "team_members" tm
    INNER JOIN "users" u ON tm."userId" = u.id
    WHERE tm."teamId" = $1
    ORDER BY
      CASE tm.role
        WHEN 'owner' THEN 1
        WHEN 'admin' THEN 2
        WHEN 'member' THEN 3
        WHEN 'viewer' THEN 4
      END,
      tm."joinedAt" ASC`,
    [teamId],
    userId
  );
  return members;
}
async function isSlugAvailable(slug, excludeTeamId) {
  let query = 'SELECT id FROM "teams" WHERE slug = $1';
  const params = [slug];
  if (excludeTeamId) {
    query += " AND id != $2";
    params.push(excludeTeamId);
  }
  query += " LIMIT 1";
  const existing = await queryOneWithRLS(query, params);
  return !existing;
}
async function switchActiveTeam(userId, teamId) {
  const isMember = await isTeamMember(userId, teamId);
  if (!isMember) {
    throw new Error("User is not a member of this team");
  }
  console.log(`User ${userId} switched to team ${teamId}`);
  return true;
}
async function deleteTeam(teamId, userId) {
  const hasPermission = await checkTeamPermission(userId, teamId, ["owner"]);
  if (!hasPermission) {
    throw new Error("Only team owner can delete the team");
  }
  const team = await queryOneWithRLS(
    'SELECT * FROM "teams" WHERE id = $1',
    [teamId],
    userId
  );
  if (!team) {
    throw new Error("Team not found");
  }
  await queryWithRLS(
    'DELETE FROM "teams" WHERE id = $1',
    [teamId],
    userId
  );
  console.log(`Team ${teamId} deleted by user ${userId}`);
}
export {
  addUserToGlobalTeam,
  checkTeamPermission,
  createTeam,
  deleteTeam,
  getGlobalTeam,
  getTeamMembersWithUsers,
  getTeamWithMemberCount,
  getUserTeamRole,
  getUserTeamsWithDetails,
  hasGlobalTeam,
  isSlugAvailable,
  isTeamMember,
  switchActiveTeam
};
